Add Allianties: persistent Tank Turn Tactics web game.
PHP engine and API (lobby, jury, shrinking arena, cease-fire, visibility, AP loot, per-lobby AP time), JS client with i18n (10 locales), 24-hour cease-fire clock, live countdowns, polling, timeline playback with arrows and t1154 controls, and BlueGit CI/FTP deploy like Meteors.
@@ -0,0 +1,16 @@
1
node_modules/
2
*.log
3
.DS_Store
4
__pycache__/
5
*.pyc
6
7
# Generated by src/build.sh — sources live in server/.
8
build/api.php
9
build/auth.php
10
build/callback.php
11
build/logout.php
12
build/router.php
13
build/.htaccess
14
build/lib/
15
build/data/
16
build/game.js
@@ -0,0 +1,16 @@1
node_modules/2
*.log3
.DS_Store4
__pycache__/5
*.pyc6
7
# Generated by src/build.sh — sources live in server/.8
build/api.php9
build/auth.php10
build/callback.php11
build/logout.php12
build/router.php13
build/.htaccess14
build/lib/15
build/data/16
build/game.js@@ -0,0 +1,95 @@
1
# Allianties
2
3
Webspel naar de basisregels van *Tank Turn Tactics* (Halfbrick). Gebouwd voor
4
[projects.timfalken.com](https://projects.timfalken.com/allianties/). De
5
spelnaam blijft in elke taal **Allianties**.
6
7
Live (na de eerste deploy): https://projects.timfalken.com/allianties/
8
9
## Spelen
10
11
1. Log in met je account op [auth.timfalken.com](https://auth.timfalken.com).
12
2. Maak een lobby of voer een uitnodigingscode in. Deel de link of de code.
13
3. De host start het spel zodra er minstens twee spelers zijn. Het spel blijft
14
daarna lopen, dagenlang, tot er één overlevende is.
15
4. Elke tank begint met 3 levens, bereik 2 (Chebyshev, ook diagonaal) en 1
16
actiepunt. Elke dag op het ingestelde tijdstip (Europe/Amsterdam, standaard 00:00) krijgt elke levende
17
speler 1 actiepunt erbij.
18
5. Voor 1 actiepunt kun je: één vakje bewegen (8 richtingen, niet op een bezet
19
of onbegaanbaar vakje), een speler binnen bereik beschieten (−1 leven), je
20
bereik met 1 vergroten, of actiepunten geven aan een speler binnen bereik.
21
6. Bij 0 levens ben je uitgeschakeld. De laatste overlevende wint. Overgeven
22
kan via het instellingenmenu, na een duidelijke bevestiging.
23
24
Optionele regels (in de lobby, vóór de start):
25
26
- **Jury** (standaard aan): dode spelers stemmen dagelijks op één levende
27
speler. Wie de meeste stemmen heeft, krijgt +1 actiepunt bij de volgende
28
uitdeling. Stemmen zijn geheim en tot de uitdeling te wijzigen.
29
- **Krimpend speelveld** (standaard uit): na een instelbaar aantal dagen
30
(standaard 7) wordt de buitenste ring onbegaanbaar. Spelers die erop staan
31
verliezen een leven en worden naar binnen geduwd.
32
- **Gedwongen staakt-het-vuren** (standaard uit): in door de host gekozen
33
uren (Europe/Amsterdam) mag niemand schieten. De periodes zijn te tekenen
34
op een 24-uursklok.
35
- **Actiepunten plunderen bij een kill** (standaard uit): alleen bij een
36
uitschakelend schot krijgt de schutter de resterende AP van het doelwit.
37
- **Dagelijks AP-tijdstip**: per lobby instelbaar (Europe/Amsterdam),
38
standaard 00:00. Jury en krimp vallen samen met dit tijdstip.
39
- **Zichtbaarheid** (standaard alles openbaar): de host bepaalt wie schoten,
40
giften, actiepuntentotalen, bereik en levens ziet. De server filtert de
41
staat en de tijdlijn per kijker. Eigen gegevens en verplaatsingen blijven
42
altijd zichtbaar.
43
44
Events staan niet in een tekstlog: je ziet ze alleen in de video-weergave
45
van de tijdlijn (groene pijl bij een gift, rode pijl bij een schot, een
46
schuivende pion bij een zet, een pulsering bij een bereik-upgrade). Klik
47
of tik ergens op de balk om naar het dichtstbijzijnde event te springen;
48
slepen scrubt, ook met touch.
49
50
De aannames bij deze regels staan in [`docs/ASSUMPTIONS.md`](docs/ASSUMPTIONS.md).
51
52
## Lokaal bouwen en draaien
53
54
```bash
55
# Tests
56
node --test test/*.test.js
57
php server/tests/run.php
58
59
# Bundel (src/ → build/game.js) en kopieer de PHP-API naar build/
60
./src/build.sh
61
# of: npm run build
62
63
# Met API (lokale testers: auth.php?test=1 tot ?test=8)
64
php -S 127.0.0.1:8080 -t build build/router.php
65
# spel: http://127.0.0.1:8080/
66
```
67
68
De testlogins (`auth.php?test=1` … `?test=8`) werken alleen op localhost en
69
zijn op de live site uitgeschakeld.
70
71
## Architectuur
72
73
| Pad | Rol |
74
| --- | --- |
75
| `src/i18n.js` | Vertalingen en vlaggenkiezer (Engels als standaard, 10 talen) |
76
| `src/rules.js` | Client-spiegel van raster, Chebyshev, staakt-het-vuren (incl. zomertijd) |
77
| `src/api.js` | API-client, CSRF, lichte `sync`-poll |
78
| `src/main.js` | Menu, lobby, bord, tijdlijn, klok-editor, countdowns |
79
| `server/lib/Engine.php` | Authoritatieve regelmotor: zetten, jury, krimp, staakt-het-vuren, einde |
80
| `server/lib/Store.php` | SQLite, `BEGIN IMMEDIATE`, JSON-game, profielen |
81
| `server/lib/i18n.json` | Gedeelde catalogus (JS en PHP) |
82
| `docs/ASSUMPTIONS.md` | Alle aannames waar de specificatie ruimte liet |
83
| `src/build.sh` | Bundelt bronnen naar `build/` |
84
| `ci/` | FTP-deploy **zonder** `--delete`. Expandeert `$timftproot`. Raakt `favicon.ico` en `data/` niet aan. |
85
86
De server is leidend bij elke actie. De client toont legale zetten die de
87
server meestuurt en speelt de tijdlijn af uit het eventlog.
88
89
## Vertalingen
90
91
Standaardtaal is Engels. Rechtsonder kies je een van tien talen via de vlag
92
(Verenigd Koninkrijk, Nederland, Duitsland, Frankrijk, Japan, China, Korea,
93
Polen, Rusland, Spanje). De keuze staat in `localStorage` en, als je
94
ingelogd bent, in je profiel, en wordt bij inloggen weer toegepast. De
95
spelnaam blijft altijd **Allianties**.
@@ -0,0 +1,95 @@1
# Allianties2
3
Webspel naar de basisregels van *Tank Turn Tactics* (Halfbrick). Gebouwd voor4
[projects.timfalken.com](https://projects.timfalken.com/allianties/). De5
spelnaam blijft in elke taal **Allianties**.6
7
Live (na de eerste deploy): https://projects.timfalken.com/allianties/8
9
## Spelen10
11
1. Log in met je account op [auth.timfalken.com](https://auth.timfalken.com).12
2. Maak een lobby of voer een uitnodigingscode in. Deel de link of de code.13
3. De host start het spel zodra er minstens twee spelers zijn. Het spel blijft14
daarna lopen, dagenlang, tot er één overlevende is.15
4. Elke tank begint met 3 levens, bereik 2 (Chebyshev, ook diagonaal) en 116
actiepunt. Elke dag op het ingestelde tijdstip (Europe/Amsterdam, standaard 00:00) krijgt elke levende17
speler 1 actiepunt erbij.18
5. Voor 1 actiepunt kun je: één vakje bewegen (8 richtingen, niet op een bezet19
of onbegaanbaar vakje), een speler binnen bereik beschieten (−1 leven), je20
bereik met 1 vergroten, of actiepunten geven aan een speler binnen bereik.21
6. Bij 0 levens ben je uitgeschakeld. De laatste overlevende wint. Overgeven22
kan via het instellingenmenu, na een duidelijke bevestiging.23
24
Optionele regels (in de lobby, vóór de start):25
26
- **Jury** (standaard aan): dode spelers stemmen dagelijks op één levende27
speler. Wie de meeste stemmen heeft, krijgt +1 actiepunt bij de volgende28
uitdeling. Stemmen zijn geheim en tot de uitdeling te wijzigen.29
- **Krimpend speelveld** (standaard uit): na een instelbaar aantal dagen30
(standaard 7) wordt de buitenste ring onbegaanbaar. Spelers die erop staan31
verliezen een leven en worden naar binnen geduwd.32
- **Gedwongen staakt-het-vuren** (standaard uit): in door de host gekozen33
uren (Europe/Amsterdam) mag niemand schieten. De periodes zijn te tekenen34
op een 24-uursklok.35
- **Actiepunten plunderen bij een kill** (standaard uit): alleen bij een36
uitschakelend schot krijgt de schutter de resterende AP van het doelwit.37
- **Dagelijks AP-tijdstip**: per lobby instelbaar (Europe/Amsterdam),38
standaard 00:00. Jury en krimp vallen samen met dit tijdstip.39
- **Zichtbaarheid** (standaard alles openbaar): de host bepaalt wie schoten,40
giften, actiepuntentotalen, bereik en levens ziet. De server filtert de41
staat en de tijdlijn per kijker. Eigen gegevens en verplaatsingen blijven42
altijd zichtbaar.43
44
Events staan niet in een tekstlog: je ziet ze alleen in de video-weergave45
van de tijdlijn (groene pijl bij een gift, rode pijl bij een schot, een46
schuivende pion bij een zet, een pulsering bij een bereik-upgrade). Klik47
of tik ergens op de balk om naar het dichtstbijzijnde event te springen;48
slepen scrubt, ook met touch.49
50
De aannames bij deze regels staan in [`docs/ASSUMPTIONS.md`](docs/ASSUMPTIONS.md).51
52
## Lokaal bouwen en draaien53
54
```bash55
# Tests56
node --test test/*.test.js57
php server/tests/run.php58
59
# Bundel (src/ → build/game.js) en kopieer de PHP-API naar build/60
./src/build.sh61
# of: npm run build62
63
# Met API (lokale testers: auth.php?test=1 tot ?test=8)64
php -S 127.0.0.1:8080 -t build build/router.php65
# spel: http://127.0.0.1:8080/66
```67
68
De testlogins (`auth.php?test=1` … `?test=8`) werken alleen op localhost en69
zijn op de live site uitgeschakeld.70
71
## Architectuur72
73
| Pad | Rol |74
| --- | --- |75
| `src/i18n.js` | Vertalingen en vlaggenkiezer (Engels als standaard, 10 talen) |76
| `src/rules.js` | Client-spiegel van raster, Chebyshev, staakt-het-vuren (incl. zomertijd) |77
| `src/api.js` | API-client, CSRF, lichte `sync`-poll |78
| `src/main.js` | Menu, lobby, bord, tijdlijn, klok-editor, countdowns |79
| `server/lib/Engine.php` | Authoritatieve regelmotor: zetten, jury, krimp, staakt-het-vuren, einde |80
| `server/lib/Store.php` | SQLite, `BEGIN IMMEDIATE`, JSON-game, profielen |81
| `server/lib/i18n.json` | Gedeelde catalogus (JS en PHP) |82
| `docs/ASSUMPTIONS.md` | Alle aannames waar de specificatie ruimte liet |83
| `src/build.sh` | Bundelt bronnen naar `build/` |84
| `ci/` | FTP-deploy **zonder** `--delete`. Expandeert `$timftproot`. Raakt `favicon.ico` en `data/` niet aan. |85
86
De server is leidend bij elke actie. De client toont legale zetten die de87
server meestuurt en speelt de tijdlijn af uit het eventlog.88
89
## Vertalingen90
91
Standaardtaal is Engels. Rechtsonder kies je een van tien talen via de vlag92
(Verenigd Koninkrijk, Nederland, Duitsland, Frankrijk, Japan, China, Korea,93
Polen, Rusland, Spanje). De keuze staat in `localStorage` en, als je94
ingelogd bent, in je profiel, en wordt bij inloggen weer toegepast. De95
spelnaam blijft altijd **Allianties**.@@ -0,0 +1,114 @@
1
# BlueGit CI for Allianties: unit tests, build of build/, FTP deploy of build/.
2
# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
3
# Repo secrets (protected, master only):
4
# projectftp — $timftproot/allianties
5
# auth_client_secret — existing auth.timfalken.com client secret for
6
# client_id projects.timfalken.com. If non-empty, deploy writes
7
# data/config.php (never logged). If empty/unset, an existing file
8
# is left alone. Optional: auth_client_id (defaults to that client_id).
9
# GEEN mirror --delete: live files mogen niet verdwijnen.
10
# Deployt map build/ (NIET de repo-root). data/ (sqlite, sessies) wordt
11
# niet gespiegeld; data/.htaccess wordt naderhand gezet, en config.php
12
# alleen vanuit het CI-geheim.
13
# favicon.ico wordt nooit geüpload.
14
stages: [test, build, deploy]
15
16
workflow:
17
rules:
18
- if: $CI_COMMIT_TAG != ""
19
when: never
20
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
21
- if: $CI_COMMIT_BRANCH == "master"
22
- if: $CI_COMMIT_BRANCH =~ /^feature\//
23
24
unit_tests:
25
stage: test
26
image: node:20-bookworm
27
script:
28
- apt-get update -qq && apt-get install -y -qq php-cli php-sqlite3 php-curl php-mbstring python3 >/dev/null
29
- node --test test/*.test.js
30
- python3 ci/test_deploy_auth.py
31
- php server/tests/run.php
32
33
build_game:
34
stage: build
35
image: debian:bookworm-slim
36
needs: [unit_tests]
37
script:
38
- apt-get update -qq && apt-get install -y -qq bash ca-certificates >/dev/null
39
- chmod +x src/build.sh
40
- ./src/build.sh
41
- test -f build/game.js
42
- test -f build/index.html
43
- test -f build/style.css
44
- test -f build/api.php
45
- test -f build/auth.php
46
- test -f build/callback.php
47
- test -f build/logout.php
48
- test -f build/.htaccess
49
- test -f build/lib/bootstrap.php
50
- test -f build/lib/Store.php
51
- test -f build/lib/Engine.php
52
- test -f build/lib/i18n.json
53
- test -f build/lib/I18n.php
54
- test -f build/images/flags/gb.svg
55
- test -f build/images/flags/nl.svg
56
- test -f build/images/flags/jp.svg
57
- test -f build/images/avatars/test_user_1.svg
58
- test -f build/data/.htaccess
59
- test ! -f build/data/config.php
60
- test ! -e build/data/*.sqlite
61
artifacts:
62
paths:
63
- build/game.js
64
- build/index.html
65
- build/style.css
66
- build/favicon.ico
67
- build/images/favicon-16.png
68
- build/images/favicon-32.png
69
- build/images/flags/gb.svg
70
- build/images/flags/nl.svg
71
- build/images/flags/de.svg
72
- build/images/flags/fr.svg
73
- build/images/flags/jp.svg
74
- build/images/flags/cn.svg
75
- build/images/flags/kr.svg
76
- build/images/flags/pl.svg
77
- build/images/flags/ru.svg
78
- build/images/flags/es.svg
79
- build/images/avatars/test_user_1.svg
80
- build/images/avatars/test_user_2.svg
81
- build/images/avatars/test_user_3.svg
82
- build/images/avatars/test_user_4.svg
83
- build/images/avatars/test_user_5.svg
84
- build/images/avatars/test_user_6.svg
85
- build/images/avatars/test_user_7.svg
86
- build/images/avatars/test_user_8.svg
87
- build/api.php
88
- build/auth.php
89
- build/callback.php
90
- build/logout.php
91
- build/.htaccess
92
- build/lib/bootstrap.php
93
- build/lib/Store.php
94
- build/lib/Engine.php
95
- build/lib/i18n.json
96
- build/lib/I18n.php
97
- build/data/.htaccess
98
expire_in: 7d
99
100
ftp_upload:
101
stage: deploy
102
image: debian:bookworm-slim
103
needs: [build_game]
104
resource_group: production
105
environment:
106
name: production
107
url: https://projects.timfalken.com/allianties/
108
rules:
109
- if: $CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"
110
script:
111
- apt-get update -qy
112
- apt-get install -y --no-install-recommends lftp python3 ca-certificates
113
- python3 ci/deploy_guard.py
114
- python3 ci/deploy.py
@@ -0,0 +1,114 @@1
# BlueGit CI for Allianties: unit tests, build of build/, FTP deploy of build/.2
# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).3
# Repo secrets (protected, master only):4
# projectftp — $timftproot/allianties5
# auth_client_secret — existing auth.timfalken.com client secret for6
# client_id projects.timfalken.com. If non-empty, deploy writes7
# data/config.php (never logged). If empty/unset, an existing file8
# is left alone. Optional: auth_client_id (defaults to that client_id).9
# GEEN mirror --delete: live files mogen niet verdwijnen.10
# Deployt map build/ (NIET de repo-root). data/ (sqlite, sessies) wordt11
# niet gespiegeld; data/.htaccess wordt naderhand gezet, en config.php12
# alleen vanuit het CI-geheim.13
# favicon.ico wordt nooit geüpload.14
stages: [test, build, deploy]15
16
workflow:17
rules:18
- if: $CI_COMMIT_TAG != ""19
when: never20
- if: $CI_PIPELINE_SOURCE == "merge_request_event"21
- if: $CI_COMMIT_BRANCH == "master"22
- if: $CI_COMMIT_BRANCH =~ /^feature\//23
24
unit_tests:25
stage: test26
image: node:20-bookworm27
script:28
- apt-get update -qq && apt-get install -y -qq php-cli php-sqlite3 php-curl php-mbstring python3 >/dev/null29
- node --test test/*.test.js30
- python3 ci/test_deploy_auth.py31
- php server/tests/run.php32
33
build_game:34
stage: build35
image: debian:bookworm-slim36
needs: [unit_tests]37
script:38
- apt-get update -qq && apt-get install -y -qq bash ca-certificates >/dev/null39
- chmod +x src/build.sh40
- ./src/build.sh41
- test -f build/game.js42
- test -f build/index.html43
- test -f build/style.css44
- test -f build/api.php45
- test -f build/auth.php46
- test -f build/callback.php47
- test -f build/logout.php48
- test -f build/.htaccess49
- test -f build/lib/bootstrap.php50
- test -f build/lib/Store.php51
- test -f build/lib/Engine.php52
- test -f build/lib/i18n.json53
- test -f build/lib/I18n.php54
- test -f build/images/flags/gb.svg55
- test -f build/images/flags/nl.svg56
- test -f build/images/flags/jp.svg57
- test -f build/images/avatars/test_user_1.svg58
- test -f build/data/.htaccess59
- test ! -f build/data/config.php60
- test ! -e build/data/*.sqlite61
artifacts:62
paths:63
- build/game.js64
- build/index.html65
- build/style.css66
- build/favicon.ico67
- build/images/favicon-16.png68
- build/images/favicon-32.png69
- build/images/flags/gb.svg70
- build/images/flags/nl.svg71
- build/images/flags/de.svg72
- build/images/flags/fr.svg73
- build/images/flags/jp.svg74
- build/images/flags/cn.svg75
- build/images/flags/kr.svg76
- build/images/flags/pl.svg77
- build/images/flags/ru.svg78
- build/images/flags/es.svg79
- build/images/avatars/test_user_1.svg80
- build/images/avatars/test_user_2.svg81
- build/images/avatars/test_user_3.svg82
- build/images/avatars/test_user_4.svg83
- build/images/avatars/test_user_5.svg84
- build/images/avatars/test_user_6.svg85
- build/images/avatars/test_user_7.svg86
- build/images/avatars/test_user_8.svg87
- build/api.php88
- build/auth.php89
- build/callback.php90
- build/logout.php91
- build/.htaccess92
- build/lib/bootstrap.php93
- build/lib/Store.php94
- build/lib/Engine.php95
- build/lib/i18n.json96
- build/lib/I18n.php97
- build/data/.htaccess98
expire_in: 7d99
100
ftp_upload:101
stage: deploy102
image: debian:bookworm-slim103
needs: [build_game]104
resource_group: production105
environment:106
name: production107
url: https://projects.timfalken.com/allianties/108
rules:109
- if: $CI_COMMIT_BRANCH == "master" && $CI_PIPELINE_SOURCE != "merge_request_event"110
script:111
- apt-get update -qy112
- apt-get install -y --no-install-recommends lftp python3 ca-certificates113
- python3 ci/deploy_guard.py114
- python3 ci/deploy.pyThe contents of this binary file are not shown.
@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#e74c3c"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T1</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#e74c3c"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T1</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#3498db"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T2</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#3498db"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T2</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#2ecc71"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T3</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#2ecc71"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T3</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#f1c40f"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T4</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#f1c40f"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T4</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#9b59b6"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T5</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#9b59b6"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T5</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#e67e22"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T6</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#e67e22"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T6</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#1abc9c"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T7</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#1abc9c"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T7</text>4
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
<circle cx="64" cy="64" r="64" fill="#e91e63"/>
3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T8</text>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">2
<circle cx="64" cy="64" r="64" fill="#e91e63"/>3
<text x="64" y="76" text-anchor="middle" font-family="sans-serif" font-size="44" font-weight="700" fill="#fff">T8</text>4
</svg>The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -0,0 +1,11 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="40" fill="#DE2910"/>
3
<g fill="#FFDE00">
4
<polygon points="10,8 11.76,13.43 17.51,13.43 12.87,16.79 14.63,22.22 10,18.86 5.37,22.22 7.13,16.79 2.49,13.43 8.24,13.43"/>
5
<!-- four smaller stars pointing toward the large one -->
6
<g transform="translate(20,6) scale(0.35) rotate(25)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>
7
<g transform="translate(24,12) scale(0.35) rotate(-20)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>
8
<g transform="translate(24,18.5) scale(0.35) rotate(-40)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>
9
<g transform="translate(20,23.5) scale(0.35) rotate(-65)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>
10
</g>
11
</svg>
@@ -0,0 +1,11 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="40" fill="#DE2910"/>3
<g fill="#FFDE00">4
<polygon points="10,8 11.76,13.43 17.51,13.43 12.87,16.79 14.63,22.22 10,18.86 5.37,22.22 7.13,16.79 2.49,13.43 8.24,13.43"/>5
<!-- four smaller stars pointing toward the large one -->6
<g transform="translate(20,6) scale(0.35) rotate(25)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>7
<g transform="translate(24,12) scale(0.35) rotate(-20)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>8
<g transform="translate(24,18.5) scale(0.35) rotate(-40)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>9
<g transform="translate(20,23.5) scale(0.35) rotate(-65)"><polygon points="0,-6 1.76,-1.85 6.12,-1.85 2.7,0.7 4.04,4.85 0,2.2 -4.04,4.85 -2.7,0.7 -6.12,-1.85 -1.76,-1.85"/></g>10
</g>11
</svg>@@ -0,0 +1,5 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="13.34" y="0" fill="#000"/>
3
<rect width="60" height="13.33" y="13.34" fill="#DD0000"/>
4
<rect width="60" height="13.33" y="26.67" fill="#FFCE00"/>
5
</svg>
@@ -0,0 +1,5 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="13.34" y="0" fill="#000"/>3
<rect width="60" height="13.33" y="13.34" fill="#DD0000"/>4
<rect width="60" height="13.33" y="26.67" fill="#FFCE00"/>5
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="40" fill="#C60B1E"/>
3
<rect width="60" height="20" y="10" fill="#FFC400"/>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="40" fill="#C60B1E"/>3
<rect width="60" height="20" y="10" fill="#FFC400"/>4
</svg>@@ -0,0 +1,5 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="20" height="40" x="0" fill="#002395"/>
3
<rect width="20" height="40" x="20" fill="#FFF"/>
4
<rect width="20" height="40" x="40" fill="#ED2939"/>
5
</svg>
@@ -0,0 +1,5 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="20" height="40" x="0" fill="#002395"/>3
<rect width="20" height="40" x="20" fill="#FFF"/>4
<rect width="20" height="40" x="40" fill="#ED2939"/>5
</svg>@@ -0,0 +1,12 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="40" fill="#012169"/>
3
<!-- white saltire -->
4
<path d="M0,0 L60,40 M60,0 L0,40" stroke="#fff" stroke-width="8"/>
5
<!-- red saltire, fimbriated by being thinner; counterchanged approximation -->
6
<path d="M0,0 L60,40" stroke="#C8102E" stroke-width="2.8"/>
7
<path d="M60,0 L0,40" stroke="#C8102E" stroke-width="2.8"/>
8
<!-- white cross -->
9
<path d="M30,0 V40 M0,20 H60" stroke="#fff" stroke-width="13.3"/>
10
<!-- red cross -->
11
<path d="M30,0 V40 M0,20 H60" stroke="#C8102E" stroke-width="8"/>
12
</svg>
@@ -0,0 +1,12 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="40" fill="#012169"/>3
<!-- white saltire -->4
<path d="M0,0 L60,40 M60,0 L0,40" stroke="#fff" stroke-width="8"/>5
<!-- red saltire, fimbriated by being thinner; counterchanged approximation -->6
<path d="M0,0 L60,40" stroke="#C8102E" stroke-width="2.8"/>7
<path d="M60,0 L0,40" stroke="#C8102E" stroke-width="2.8"/>8
<!-- white cross -->9
<path d="M30,0 V40 M0,20 H60" stroke="#fff" stroke-width="13.3"/>10
<!-- red cross -->11
<path d="M30,0 V40 M0,20 H60" stroke="#C8102E" stroke-width="8"/>12
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="40" fill="#FFF"/>
3
<circle cx="30" cy="20" r="12" fill="#BC002D"/>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="40" fill="#FFF"/>3
<circle cx="30" cy="20" r="12" fill="#BC002D"/>4
</svg>@@ -0,0 +1,31 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="40" fill="#FFF"/>
3
<!-- Taegeuk -->
4
<g transform="translate(30,20) rotate(-56.3)">
5
<path d="M0,-8 A8,8 0 0,1 0,8 A4,4 0 0,1 0,0 A4,4 0 0,0 0,-8 Z" fill="#CD2E3A"/>
6
<path d="M0,8 A8,8 0 0,1 0,-8 A4,4 0 0,1 0,0 A4,4 0 0,0 0,8 Z" fill="#0047A0"/>
7
<circle cx="0" cy="-4" r="4" fill="#CD2E3A"/>
8
<circle cx="0" cy="4" r="4" fill="#0047A0"/>
9
</g>
10
<!-- Trigrams: geon (☰) top-left, gon (☷) bottom-right, gam (☵) top-right, ri (☲) bottom-left -->
11
<g fill="#000" transform="translate(14,8) rotate(-56.3)">
12
<rect x="-6.5" y="-5.5" width="13" height="2.2"/>
13
<rect x="-6.5" y="-1.1" width="13" height="2.2"/>
14
<rect x="-6.5" y="3.3" width="13" height="2.2"/>
15
</g>
16
<g fill="#000" transform="translate(46,32) rotate(-56.3)">
17
<rect x="-6.5" y="-5.5" width="5.8" height="2.2"/><rect x="0.7" y="-5.5" width="5.8" height="2.2"/>
18
<rect x="-6.5" y="-1.1" width="5.8" height="2.2"/><rect x="0.7" y="-1.1" width="5.8" height="2.2"/>
19
<rect x="-6.5" y="3.3" width="5.8" height="2.2"/><rect x="0.7" y="3.3" width="5.8" height="2.2"/>
20
</g>
21
<g fill="#000" transform="translate(46,8) rotate(56.3)">
22
<rect x="-6.5" y="-5.5" width="5.8" height="2.2"/><rect x="0.7" y="-5.5" width="5.8" height="2.2"/>
23
<rect x="-6.5" y="-1.1" width="13" height="2.2"/>
24
<rect x="-6.5" y="3.3" width="5.8" height="2.2"/><rect x="0.7" y="3.3" width="5.8" height="2.2"/>
25
</g>
26
<g fill="#000" transform="translate(14,32) rotate(56.3)">
27
<rect x="-6.5" y="-5.5" width="13" height="2.2"/>
28
<rect x="-6.5" y="-1.1" width="5.8" height="2.2"/><rect x="0.7" y="-1.1" width="5.8" height="2.2"/>
29
<rect x="-6.5" y="3.3" width="13" height="2.2"/>
30
</g>
31
</svg>
@@ -0,0 +1,31 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="40" fill="#FFF"/>3
<!-- Taegeuk -->4
<g transform="translate(30,20) rotate(-56.3)">5
<path d="M0,-8 A8,8 0 0,1 0,8 A4,4 0 0,1 0,0 A4,4 0 0,0 0,-8 Z" fill="#CD2E3A"/>6
<path d="M0,8 A8,8 0 0,1 0,-8 A4,4 0 0,1 0,0 A4,4 0 0,0 0,8 Z" fill="#0047A0"/>7
<circle cx="0" cy="-4" r="4" fill="#CD2E3A"/>8
<circle cx="0" cy="4" r="4" fill="#0047A0"/>9
</g>10
<!-- Trigrams: geon (☰) top-left, gon (☷) bottom-right, gam (☵) top-right, ri (☲) bottom-left -->11
<g fill="#000" transform="translate(14,8) rotate(-56.3)">12
<rect x="-6.5" y="-5.5" width="13" height="2.2"/>13
<rect x="-6.5" y="-1.1" width="13" height="2.2"/>14
<rect x="-6.5" y="3.3" width="13" height="2.2"/>15
</g>16
<g fill="#000" transform="translate(46,32) rotate(-56.3)">17
<rect x="-6.5" y="-5.5" width="5.8" height="2.2"/><rect x="0.7" y="-5.5" width="5.8" height="2.2"/>18
<rect x="-6.5" y="-1.1" width="5.8" height="2.2"/><rect x="0.7" y="-1.1" width="5.8" height="2.2"/>19
<rect x="-6.5" y="3.3" width="5.8" height="2.2"/><rect x="0.7" y="3.3" width="5.8" height="2.2"/>20
</g>21
<g fill="#000" transform="translate(46,8) rotate(56.3)">22
<rect x="-6.5" y="-5.5" width="5.8" height="2.2"/><rect x="0.7" y="-5.5" width="5.8" height="2.2"/>23
<rect x="-6.5" y="-1.1" width="13" height="2.2"/>24
<rect x="-6.5" y="3.3" width="5.8" height="2.2"/><rect x="0.7" y="3.3" width="5.8" height="2.2"/>25
</g>26
<g fill="#000" transform="translate(14,32) rotate(56.3)">27
<rect x="-6.5" y="-5.5" width="13" height="2.2"/>28
<rect x="-6.5" y="-1.1" width="5.8" height="2.2"/><rect x="0.7" y="-1.1" width="5.8" height="2.2"/>29
<rect x="-6.5" y="3.3" width="13" height="2.2"/>30
</g>31
</svg>@@ -0,0 +1,5 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="13.34" y="0" fill="#AE1C28"/>
3
<rect width="60" height="13.33" y="13.34" fill="#FFF"/>
4
<rect width="60" height="13.33" y="26.67" fill="#21468B"/>
5
</svg>
@@ -0,0 +1,5 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="13.34" y="0" fill="#AE1C28"/>3
<rect width="60" height="13.33" y="13.34" fill="#FFF"/>4
<rect width="60" height="13.33" y="26.67" fill="#21468B"/>5
</svg>@@ -0,0 +1,4 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="20" y="0" fill="#FFF"/>
3
<rect width="60" height="20" y="20" fill="#DC143C"/>
4
</svg>
@@ -0,0 +1,4 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="20" y="0" fill="#FFF"/>3
<rect width="60" height="20" y="20" fill="#DC143C"/>4
</svg>@@ -0,0 +1,5 @@
1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">
2
<rect width="60" height="13.34" y="0" fill="#FFF"/>
3
<rect width="60" height="13.33" y="13.34" fill="#0039A6"/>
4
<rect width="60" height="13.33" y="26.67" fill="#D52B1E"/>
5
</svg>
@@ -0,0 +1,5 @@1
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 40" width="60" height="40">2
<rect width="60" height="13.34" y="0" fill="#FFF"/>3
<rect width="60" height="13.33" y="13.34" fill="#0039A6"/>4
<rect width="60" height="13.33" y="26.67" fill="#D52B1E"/>5
</svg>@@ -0,0 +1,255 @@
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="utf-8">
5
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
6
<meta name="apple-mobile-web-app-capable" content="yes">
7
<meta name="mobile-web-app-capable" content="yes">
8
<meta name="theme-color" content="#0c1020">
9
<link rel="icon" href="favicon.ico" sizes="any">
10
<title>Allianties</title>
11
<link rel="stylesheet" href="style.css">
12
</head>
13
<body>
14
<div id="app">
15
<header id="top-bar" hidden>
16
<div id="top-title">Allianties</div>
17
<div id="countdowns">
18
<div id="ap-countdown" class="countdown">
19
<span class="cd-label" data-i18n="game.nextAp">Next action points</span>
20
<span id="ap-hms" class="cd-hms">00:00:00</span>
21
</div>
22
<div id="cf-countdown" class="countdown" hidden>
23
<span id="cf-label" class="cd-label"></span>
24
<span id="cf-hms" class="cd-hms">00:00:00</span>
25
</div>
26
</div>
27
<div id="top-meta">
28
<span id="day-label"></span>
29
<span id="shrink-banner" hidden></span>
30
</div>
31
</header>
32
33
<div id="menu" class="screen">
34
<h1>Allianties</h1>
35
<p class="tagline" data-i18n="menu.tagline">A game of patience, alliances and well-timed shots.</p>
36
37
<div id="menu-account" class="menu-account">
38
<p id="menu-guest">
39
<a id="menu-login" href="auth.php" class="button" data-i18n="menu.login">Log in</a>
40
<span id="menu-local-login" hidden>
41
<span data-i18n="menu.localTest">local test:</span>
42
<span id="local-links"></span>
43
</span>
44
</p>
45
<p id="menu-user" hidden>
46
<img id="menu-avatar" class="avatar-sm" alt="" width="32" height="32">
47
<span data-i18n="menu.loggedInAs">Logged in as</span>
48
<strong id="menu-name"></strong>
49
· <a id="menu-logout" href="logout.php" data-i18n="menu.logout">Log out</a>
50
</p>
51
</div>
52
53
<p id="menu-guest-hint" class="hint" data-i18n="menu.guestHint">Log in to create a lobby, invite players and start a lasting game.</p>
54
<p id="menu-unconfigured" class="notice" hidden data-i18n-html="menu.authUnconfiguredHtml"></p>
55
<p id="menu-error" class="error" hidden role="alert"></p>
56
57
<div id="menu-actions" hidden>
58
<button type="button" id="btn-create" data-i18n="menu.create">New lobby</button>
59
<form id="join-form" class="join-form" action="#">
60
<label class="sr-only" for="join-code" data-i18n="menu.codePlaceholder">Code</label>
61
<input id="join-code" name="code" type="text" autocomplete="off" spellcheck="false" maxlength="8" inputmode="text" data-i18n-placeholder="menu.codePlaceholder" placeholder="Code">
62
<button type="submit" data-i18n="menu.join">Join</button>
63
</form>
64
</div>
65
66
<section id="my-games" hidden>
67
<h2 data-i18n="menu.myGames">Your games</h2>
68
<p id="no-games" class="hint" hidden data-i18n="menu.noGames"></p>
69
<ul id="games-list" class="games-list"></ul>
70
</section>
71
</div>
72
73
<div id="lobby" class="screen" hidden>
74
<button type="button" class="btn-back" id="lobby-back" data-i18n="lobby.back">Back</button>
75
<h1 data-i18n="lobby.title">Lobby</h1>
76
<p class="tagline">
77
<span data-i18n="lobby.code">Code</span>:
78
<strong id="lobby-code" class="mono"></strong>
79
</p>
80
<p class="hint" data-i18n="lobby.shareHint">Share this code or link. Players log in and join.</p>
81
<div class="invite-row">
82
<input id="invite-link" class="mono" type="text" readonly>
83
<button type="button" id="btn-copy" class="btn-secondary" data-i18n="lobby.copy">Copy link</button>
84
</div>
85
<p id="copy-status" class="hint" hidden data-i18n="lobby.copied">Copied</p>
86
87
<section>
88
<h2 data-i18n="lobby.players">Players</h2>
89
<ul id="lobby-players" class="player-list"></ul>
90
<p id="lobby-need" class="hint" data-i18n="lobby.needTwo"></p>
91
</section>
92
93
<section id="lobby-rules" class="rules-panel">
94
<h2 data-i18n="lobby.rules">Rules</h2>
95
96
<label class="toggle">
97
<input type="checkbox" id="rule-jury" checked>
98
<span>
99
<strong data-i18n="lobby.jury">Jury</strong>
100
<small data-i18n="lobby.juryHint"></small>
101
</span>
102
</label>
103
104
<label class="toggle">
105
<input type="checkbox" id="rule-ap-loot">
106
<span>
107
<strong data-i18n="lobby.apLoot">Loot action points on a kill</strong>
108
<small data-i18n="lobby.apLootHint"></small>
109
</span>
110
</label>
111
112
<div id="ap-time-wrap" class="field ap-time-field">
113
<label for="rule-ap-time" data-i18n="lobby.apTime">Daily action points at</label>
114
<input type="time" id="rule-ap-time" value="00:00" step="60">
115
<small data-i18n="lobby.apTimeHint"></small>
116
</div>
117
118
<label class="toggle">
119
<input type="checkbox" id="rule-shrink">
120
<span>
121
<strong data-i18n="lobby.shrink">Shrinking arena</strong>
122
<small data-i18n="lobby.shrinkHint"></small>
123
</span>
124
</label>
125
<div id="shrink-days-wrap" class="field" hidden>
126
<label for="rule-shrink-days" data-i18n="lobby.shrinkDays">Days between shrinks</label>
127
<input type="number" id="rule-shrink-days" min="1" max="30" value="7" inputmode="numeric">
128
<small data-i18n="lobby.shrinkDaysHint"></small>
129
</div>
130
131
<label class="toggle">
132
<input type="checkbox" id="rule-ceasefire">
133
<span>
134
<strong data-i18n="lobby.ceasefire">Forced cease-fire hours</strong>
135
<small data-i18n="lobby.ceasefireHint"></small>
136
</span>
137
</label>
138
<div id="ceasefire-editor" class="ceasefire-editor" hidden>
139
<p class="hint" data-i18n="lobby.ceasefireClock"></p>
140
<div id="cf-clock" class="cf-clock" aria-label="24-hour clock"></div>
141
<ul id="cf-ranges" class="cf-ranges"></ul>
142
<button type="button" id="cf-add" class="btn-secondary" data-i18n="lobby.ceasefireAdd">Add period</button>
143
</div>
144
145
<div id="lobby-visibility" class="vis-panel">
146
<h3 data-i18n="lobby.visibility">Visibility</h3>
147
<p class="hint" data-i18n="lobby.visibilityHint"></p>
148
149
<fieldset class="vis-field">
150
<legend data-i18n="lobby.visShots">Shots</legend>
151
<label class="vis-opt"><input type="radio" name="vis_shots" value="public" checked> <span data-i18n="lobby.visShotsPublic">Public</span></label>
152
<label class="vis-opt"><input type="radio" name="vis_shots" value="elim_public"> <span data-i18n="lobby.visShotsElimPublic">Only eliminating shots are public</span></label>
153
<label class="vis-opt"><input type="radio" name="vis_shots" value="known_target"> <span data-i18n="lobby.visShotsKnownTarget">Known to the target</span></label>
154
<label class="vis-opt"><input type="radio" name="vis_shots" value="elim_known_target"> <span data-i18n="lobby.visShotsElimKnownTarget">Only eliminating shots are known to the target</span></label>
155
</fieldset>
156
157
<fieldset class="vis-field">
158
<legend data-i18n="lobby.visGifts">Gifts</legend>
159
<label class="vis-opt"><input type="radio" name="vis_gifts" value="public" checked> <span data-i18n="lobby.visGiftsPublic">Public</span></label>
160
<label class="vis-opt"><input type="radio" name="vis_gifts" value="known_recipient"> <span data-i18n="lobby.visGiftsKnownRecipient">Known to the recipient</span></label>
161
<label class="vis-opt"><input type="radio" name="vis_gifts" value="anonymous"> <span data-i18n="lobby.visGiftsAnonymous">Anonymous</span></label>
162
</fieldset>
163
164
<fieldset class="vis-field">
165
<legend data-i18n="lobby.visAp">Action-point totals</legend>
166
<label class="vis-opt"><input type="radio" name="vis_ap" value="public" checked> <span data-i18n="lobby.visApPublic">Public</span></label>
167
<label class="vis-opt"><input type="radio" name="vis_ap" value="hidden"> <span data-i18n="lobby.visApHidden">Hidden</span></label>
168
</fieldset>
169
170
<fieldset class="vis-field">
171
<legend data-i18n="lobby.visRange">Range</legend>
172
<label class="vis-opt"><input type="radio" name="vis_range" value="public" checked> <span data-i18n="lobby.visRangePublic">Public</span></label>
173
<label class="vis-opt"><input type="radio" name="vis_range" value="known_in_range"> <span data-i18n="lobby.visRangeInRange">Known to players within range</span></label>
174
<label class="vis-opt"><input type="radio" name="vis_range" value="hidden"> <span data-i18n="lobby.visRangeHidden">Hidden</span></label>
175
</fieldset>
176
177
<fieldset class="vis-field">
178
<legend data-i18n="lobby.visLives">Lives</legend>
179
<label class="vis-opt"><input type="radio" name="vis_lives" value="public" checked> <span data-i18n="lobby.visLivesPublic">Public</span></label>
180
<label class="vis-opt"><input type="radio" name="vis_lives" value="hidden"> <span data-i18n="lobby.visLivesHidden">Hidden</span></label>
181
</fieldset>
182
</div>
183
</section>
184
185
<p id="lobby-error" class="error" hidden role="alert"></p>
186
<div class="actions">
187
<button type="button" id="btn-start" data-i18n="lobby.start">Start game</button>
188
<button type="button" id="btn-leave" class="btn-danger-outline" data-i18n="lobby.leave">Leave lobby</button>
189
</div>
190
<p id="lobby-waiting" class="hint" hidden data-i18n="lobby.waiting"></p>
191
</div>
192
193
<div id="game" class="screen" hidden>
194
<div id="game-hud">
195
<div id="you-stats"></div>
196
<button type="button" id="btn-upgrade" hidden data-i18n="game.upgrade">Upgrade range</button>
197
<button type="button" id="btn-settings" data-i18n-aria="game.settings" title="Settings" data-i18n-title="game.settings">⚙</button>
198
</div>
199
<p id="game-banner" class="banner" hidden></p>
200
<p id="game-error" class="error" hidden role="alert"></p>
201
<div id="board-wrap">
202
<div id="board" role="grid"></div>
203
<svg id="board-fx" class="board-fx" aria-hidden="true"></svg>
204
</div>
205
<div id="jury-panel" hidden>
206
<h2 data-i18n="jury.title">Jury</h2>
207
<p class="hint" data-i18n="jury.hint"></p>
208
<ul id="jury-list"></ul>
209
</div>
210
<div id="timeline">
211
<button type="button" id="tl-back" data-i18n-aria="timeline.stepBack" title="Step back" aria-label="Step back">‹</button>
212
<button type="button" id="tl-play" data-i18n-aria="timeline.play" title="Play">▶</button>
213
<button type="button" id="tl-fwd" data-i18n-aria="timeline.stepForward" title="Step forward" aria-label="Step forward">›</button>
214
<div id="tl-track" role="slider" aria-valuemin="0" aria-valuemax="0" aria-valuenow="0" tabindex="0">
215
<div id="tl-ticks"></div>
216
<div id="tl-head"></div>
217
</div>
218
<button type="button" id="tl-live" class="btn-secondary" data-i18n="timeline.live" data-i18n-aria="timeline.live" title="Jump to present">Live</button>
219
</div>
220
<p id="tl-caption" class="hint" hidden></p>
221
</div>
222
</div>
223
224
<div id="modal" class="modal" hidden>
225
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="modal-title">
226
<button type="button" class="modal-close" id="modal-close" data-i18n-aria="opt.close">×</button>
227
<h2 id="modal-title"></h2>
228
<div id="modal-body"></div>
229
</div>
230
</div>
231
232
<div id="sheet" class="sheet" hidden>
233
<div class="sheet-card" role="dialog" aria-modal="true">
234
<div id="sheet-body"></div>
235
<button type="button" id="sheet-close" class="btn-secondary" data-i18n="opt.close">Close</button>
236
</div>
237
</div>
238
239
<div id="settings-panel" class="settings-panel" hidden>
240
<h2 data-i18n="game.settings">Settings</h2>
241
<button type="button" id="btn-surrender" class="btn-danger" data-i18n="game.surrender">Surrender</button>
242
<button type="button" id="btn-to-menu" class="btn-secondary" data-i18n="game.back">Back to menu</button>
243
<button type="button" id="settings-close" class="btn-secondary" data-i18n="opt.close">Close</button>
244
</div>
245
246
<div id="lang-picker" class="lang-picker">
247
<button type="button" id="lang-current" class="lang-current" aria-haspopup="listbox" aria-expanded="false" data-i18n-aria="lang.choose">
248
<img src="images/flags/gb.svg" alt="English" width="36" height="24">
249
</button>
250
<div id="lang-list" class="lang-list" role="listbox" hidden></div>
251
</div>
252
253
<script src="game.js"></script>
254
</body>
255
</html>
@@ -0,0 +1,255 @@1
<!DOCTYPE html>2
<html lang="en">3
<head>4
<meta charset="utf-8">5
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">6
<meta name="apple-mobile-web-app-capable" content="yes">7
<meta name="mobile-web-app-capable" content="yes">8
<meta name="theme-color" content="#0c1020">9
<link rel="icon" href="favicon.ico" sizes="any">10
<title>Allianties</title>11
<link rel="stylesheet" href="style.css">12
</head>13
<body>14
<div id="app">15
<header id="top-bar" hidden>16
<div id="top-title">Allianties</div>17
<div id="countdowns">18
<div id="ap-countdown" class="countdown">19
<span class="cd-label" data-i18n="game.nextAp">Next action points</span>20
<span id="ap-hms" class="cd-hms">00:00:00</span>21
</div>22
<div id="cf-countdown" class="countdown" hidden>23
<span id="cf-label" class="cd-label"></span>24
<span id="cf-hms" class="cd-hms">00:00:00</span>25
</div>26
</div>27
<div id="top-meta">28
<span id="day-label"></span>29
<span id="shrink-banner" hidden></span>30
</div>31
</header>32
33
<div id="menu" class="screen">34
<h1>Allianties</h1>35
<p class="tagline" data-i18n="menu.tagline">A game of patience, alliances and well-timed shots.</p>36
37
<div id="menu-account" class="menu-account">38
<p id="menu-guest">39
<a id="menu-login" href="auth.php" class="button" data-i18n="menu.login">Log in</a>40
<span id="menu-local-login" hidden>41
<span data-i18n="menu.localTest">local test:</span>42
<span id="local-links"></span>43
</span>44
</p>45
<p id="menu-user" hidden>46
<img id="menu-avatar" class="avatar-sm" alt="" width="32" height="32">47
<span data-i18n="menu.loggedInAs">Logged in as</span>48
<strong id="menu-name"></strong>49
· <a id="menu-logout" href="logout.php" data-i18n="menu.logout">Log out</a>50
</p>51
</div>52
53
<p id="menu-guest-hint" class="hint" data-i18n="menu.guestHint">Log in to create a lobby, invite players and start a lasting game.</p>54
<p id="menu-unconfigured" class="notice" hidden data-i18n-html="menu.authUnconfiguredHtml"></p>55
<p id="menu-error" class="error" hidden role="alert"></p>56
57
<div id="menu-actions" hidden>58
<button type="button" id="btn-create" data-i18n="menu.create">New lobby</button>59
<form id="join-form" class="join-form" action="#">60
<label class="sr-only" for="join-code" data-i18n="menu.codePlaceholder">Code</label>61
<input id="join-code" name="code" type="text" autocomplete="off" spellcheck="false" maxlength="8" inputmode="text" data-i18n-placeholder="menu.codePlaceholder" placeholder="Code">62
<button type="submit" data-i18n="menu.join">Join</button>63
</form>64
</div>65
66
<section id="my-games" hidden>67
<h2 data-i18n="menu.myGames">Your games</h2>68
<p id="no-games" class="hint" hidden data-i18n="menu.noGames"></p>69
<ul id="games-list" class="games-list"></ul>70
</section>71
</div>72
73
<div id="lobby" class="screen" hidden>74
<button type="button" class="btn-back" id="lobby-back" data-i18n="lobby.back">Back</button>75
<h1 data-i18n="lobby.title">Lobby</h1>76
<p class="tagline">77
<span data-i18n="lobby.code">Code</span>:78
<strong id="lobby-code" class="mono"></strong>79
</p>80
<p class="hint" data-i18n="lobby.shareHint">Share this code or link. Players log in and join.</p>81
<div class="invite-row">82
<input id="invite-link" class="mono" type="text" readonly>83
<button type="button" id="btn-copy" class="btn-secondary" data-i18n="lobby.copy">Copy link</button>84
</div>85
<p id="copy-status" class="hint" hidden data-i18n="lobby.copied">Copied</p>86
87
<section>88
<h2 data-i18n="lobby.players">Players</h2>89
<ul id="lobby-players" class="player-list"></ul>90
<p id="lobby-need" class="hint" data-i18n="lobby.needTwo"></p>91
</section>92
93
<section id="lobby-rules" class="rules-panel">94
<h2 data-i18n="lobby.rules">Rules</h2>95
96
<label class="toggle">97
<input type="checkbox" id="rule-jury" checked>98
<span>99
<strong data-i18n="lobby.jury">Jury</strong>100
<small data-i18n="lobby.juryHint"></small>101
</span>102
</label>103
104
<label class="toggle">105
<input type="checkbox" id="rule-ap-loot">106
<span>107
<strong data-i18n="lobby.apLoot">Loot action points on a kill</strong>108
<small data-i18n="lobby.apLootHint"></small>109
</span>110
</label>111
112
<div id="ap-time-wrap" class="field ap-time-field">113
<label for="rule-ap-time" data-i18n="lobby.apTime">Daily action points at</label>114
<input type="time" id="rule-ap-time" value="00:00" step="60">115
<small data-i18n="lobby.apTimeHint"></small>116
</div>117
118
<label class="toggle">119
<input type="checkbox" id="rule-shrink">120
<span>121
<strong data-i18n="lobby.shrink">Shrinking arena</strong>122
<small data-i18n="lobby.shrinkHint"></small>123
</span>124
</label>125
<div id="shrink-days-wrap" class="field" hidden>126
<label for="rule-shrink-days" data-i18n="lobby.shrinkDays">Days between shrinks</label>127
<input type="number" id="rule-shrink-days" min="1" max="30" value="7" inputmode="numeric">128
<small data-i18n="lobby.shrinkDaysHint"></small>129
</div>130
131
<label class="toggle">132
<input type="checkbox" id="rule-ceasefire">133
<span>134
<strong data-i18n="lobby.ceasefire">Forced cease-fire hours</strong>135
<small data-i18n="lobby.ceasefireHint"></small>136
</span>137
</label>138
<div id="ceasefire-editor" class="ceasefire-editor" hidden>139
<p class="hint" data-i18n="lobby.ceasefireClock"></p>140
<div id="cf-clock" class="cf-clock" aria-label="24-hour clock"></div>141
<ul id="cf-ranges" class="cf-ranges"></ul>142
<button type="button" id="cf-add" class="btn-secondary" data-i18n="lobby.ceasefireAdd">Add period</button>143
</div>144
145
<div id="lobby-visibility" class="vis-panel">146
<h3 data-i18n="lobby.visibility">Visibility</h3>147
<p class="hint" data-i18n="lobby.visibilityHint"></p>148
149
<fieldset class="vis-field">150
<legend data-i18n="lobby.visShots">Shots</legend>151
<label class="vis-opt"><input type="radio" name="vis_shots" value="public" checked> <span data-i18n="lobby.visShotsPublic">Public</span></label>152
<label class="vis-opt"><input type="radio" name="vis_shots" value="elim_public"> <span data-i18n="lobby.visShotsElimPublic">Only eliminating shots are public</span></label>153
<label class="vis-opt"><input type="radio" name="vis_shots" value="known_target"> <span data-i18n="lobby.visShotsKnownTarget">Known to the target</span></label>154
<label class="vis-opt"><input type="radio" name="vis_shots" value="elim_known_target"> <span data-i18n="lobby.visShotsElimKnownTarget">Only eliminating shots are known to the target</span></label>155
</fieldset>156
157
<fieldset class="vis-field">158
<legend data-i18n="lobby.visGifts">Gifts</legend>159
<label class="vis-opt"><input type="radio" name="vis_gifts" value="public" checked> <span data-i18n="lobby.visGiftsPublic">Public</span></label>160
<label class="vis-opt"><input type="radio" name="vis_gifts" value="known_recipient"> <span data-i18n="lobby.visGiftsKnownRecipient">Known to the recipient</span></label>161
<label class="vis-opt"><input type="radio" name="vis_gifts" value="anonymous"> <span data-i18n="lobby.visGiftsAnonymous">Anonymous</span></label>162
</fieldset>163
164
<fieldset class="vis-field">165
<legend data-i18n="lobby.visAp">Action-point totals</legend>166
<label class="vis-opt"><input type="radio" name="vis_ap" value="public" checked> <span data-i18n="lobby.visApPublic">Public</span></label>167
<label class="vis-opt"><input type="radio" name="vis_ap" value="hidden"> <span data-i18n="lobby.visApHidden">Hidden</span></label>168
</fieldset>169
170
<fieldset class="vis-field">171
<legend data-i18n="lobby.visRange">Range</legend>172
<label class="vis-opt"><input type="radio" name="vis_range" value="public" checked> <span data-i18n="lobby.visRangePublic">Public</span></label>173
<label class="vis-opt"><input type="radio" name="vis_range" value="known_in_range"> <span data-i18n="lobby.visRangeInRange">Known to players within range</span></label>174
<label class="vis-opt"><input type="radio" name="vis_range" value="hidden"> <span data-i18n="lobby.visRangeHidden">Hidden</span></label>175
</fieldset>176
177
<fieldset class="vis-field">178
<legend data-i18n="lobby.visLives">Lives</legend>179
<label class="vis-opt"><input type="radio" name="vis_lives" value="public" checked> <span data-i18n="lobby.visLivesPublic">Public</span></label>180
<label class="vis-opt"><input type="radio" name="vis_lives" value="hidden"> <span data-i18n="lobby.visLivesHidden">Hidden</span></label>181
</fieldset>182
</div>183
</section>184
185
<p id="lobby-error" class="error" hidden role="alert"></p>186
<div class="actions">187
<button type="button" id="btn-start" data-i18n="lobby.start">Start game</button>188
<button type="button" id="btn-leave" class="btn-danger-outline" data-i18n="lobby.leave">Leave lobby</button>189
</div>190
<p id="lobby-waiting" class="hint" hidden data-i18n="lobby.waiting"></p>191
</div>192
193
<div id="game" class="screen" hidden>194
<div id="game-hud">195
<div id="you-stats"></div>196
<button type="button" id="btn-upgrade" hidden data-i18n="game.upgrade">Upgrade range</button>197
<button type="button" id="btn-settings" data-i18n-aria="game.settings" title="Settings" data-i18n-title="game.settings">⚙</button>198
</div>199
<p id="game-banner" class="banner" hidden></p>200
<p id="game-error" class="error" hidden role="alert"></p>201
<div id="board-wrap">202
<div id="board" role="grid"></div>203
<svg id="board-fx" class="board-fx" aria-hidden="true"></svg>204
</div>205
<div id="jury-panel" hidden>206
<h2 data-i18n="jury.title">Jury</h2>207
<p class="hint" data-i18n="jury.hint"></p>208
<ul id="jury-list"></ul>209
</div>210
<div id="timeline">211
<button type="button" id="tl-back" data-i18n-aria="timeline.stepBack" title="Step back" aria-label="Step back">‹</button>212
<button type="button" id="tl-play" data-i18n-aria="timeline.play" title="Play">▶</button>213
<button type="button" id="tl-fwd" data-i18n-aria="timeline.stepForward" title="Step forward" aria-label="Step forward">›</button>214
<div id="tl-track" role="slider" aria-valuemin="0" aria-valuemax="0" aria-valuenow="0" tabindex="0">215
<div id="tl-ticks"></div>216
<div id="tl-head"></div>217
</div>218
<button type="button" id="tl-live" class="btn-secondary" data-i18n="timeline.live" data-i18n-aria="timeline.live" title="Jump to present">Live</button>219
</div>220
<p id="tl-caption" class="hint" hidden></p>221
</div>222
</div>223
224
<div id="modal" class="modal" hidden>225
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="modal-title">226
<button type="button" class="modal-close" id="modal-close" data-i18n-aria="opt.close">×</button>227
<h2 id="modal-title"></h2>228
<div id="modal-body"></div>229
</div>230
</div>231
232
<div id="sheet" class="sheet" hidden>233
<div class="sheet-card" role="dialog" aria-modal="true">234
<div id="sheet-body"></div>235
<button type="button" id="sheet-close" class="btn-secondary" data-i18n="opt.close">Close</button>236
</div>237
</div>238
239
<div id="settings-panel" class="settings-panel" hidden>240
<h2 data-i18n="game.settings">Settings</h2>241
<button type="button" id="btn-surrender" class="btn-danger" data-i18n="game.surrender">Surrender</button>242
<button type="button" id="btn-to-menu" class="btn-secondary" data-i18n="game.back">Back to menu</button>243
<button type="button" id="settings-close" class="btn-secondary" data-i18n="opt.close">Close</button>244
</div>245
246
<div id="lang-picker" class="lang-picker">247
<button type="button" id="lang-current" class="lang-current" aria-haspopup="listbox" aria-expanded="false" data-i18n-aria="lang.choose">248
<img src="images/flags/gb.svg" alt="English" width="36" height="24">249
</button>250
<div id="lang-list" class="lang-list" role="listbox" hidden></div>251
</div>252
253
<script src="game.js"></script>254
</body>255
</html>@@ -0,0 +1,561 @@
1
:root {
2
--bg: #0c1020;
3
--bg-2: #151a2e;
4
--bg-3: #1c2340;
5
--gold: #e8c547;
6
--gold-dim: #b8942e;
7
--ink: #e8eaf2;
8
--muted: #9aa3bd;
9
--danger: #e85d5d;
10
--ok: #4ecb8d;
11
--cf: #c44b4b;
12
--line: rgba(200, 210, 240, 0.18);
13
--safe-b: max(12px, env(safe-area-inset-bottom, 0px));
14
--safe-t: max(8px, env(safe-area-inset-top, 0px));
15
--safe-r: max(8px, env(safe-area-inset-right, 0px));
16
--safe-l: max(8px, env(safe-area-inset-left, 0px));
17
--radius: 12px;
18
--hit: 44px;
19
--font: "Source Sans 3", "Segoe UI", "Noto Sans", "Hiragino Sans", "Noto Sans CJK JP", "Noto Sans CJK SC", "Noto Sans CJK KR", sans-serif;
20
}
21
* { box-sizing: border-box; }
22
html, body {
23
margin: 0; padding: 0;
24
background: var(--bg);
25
color: var(--ink);
26
font-family: var(--font);
27
font-size: 16px;
28
line-height: 1.45;
29
min-height: 100%;
30
min-height: 100dvh;
31
-webkit-text-size-adjust: 100%;
32
touch-action: manipulation;
33
}
34
body { padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l); }
35
button, input, a.button {
36
font: inherit;
37
touch-action: manipulation;
38
}
39
button, a.button {
40
appearance: none;
41
display: inline-flex;
42
align-items: center;
43
justify-content: center;
44
min-height: var(--hit);
45
min-width: var(--hit);
46
padding: 10px 18px;
47
border: 0;
48
border-radius: 10px;
49
background: var(--gold);
50
color: #1a1404;
51
font-weight: 650;
52
cursor: pointer;
53
text-decoration: none;
54
}
55
button:disabled { opacity: 0.45; cursor: not-allowed; }
56
button:focus-visible, a.button:focus-visible, input:focus-visible {
57
outline: 2px solid var(--gold);
58
outline-offset: 2px;
59
}
60
.btn-secondary, .btn-secondary:link {
61
background: var(--bg-3);
62
color: var(--ink);
63
border: 1px solid var(--line);
64
}
65
.btn-danger { background: var(--danger); color: #fff; }
66
.btn-danger-outline {
67
background: transparent;
68
color: var(--danger);
69
border: 1px solid var(--danger);
70
}
71
.btn-back {
72
background: transparent;
73
color: var(--muted);
74
border: 1px solid var(--line);
75
min-width: auto;
76
margin-bottom: 8px;
77
}
78
input[type="text"], input[type="number"], input[type="time"], textarea {
79
background: var(--bg-2);
80
color: var(--ink);
81
border: 1px solid var(--line);
82
border-radius: 10px;
83
padding: 10px 12px;
84
min-height: var(--hit);
85
width: 100%;
86
}
87
.sr-only {
88
position: absolute; width: 1px; height: 1px;
89
padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0;
90
}
91
h1, h2 { font-weight: 700; letter-spacing: 0.01em; margin: 0 0 0.4em; }
92
h1 { font-size: 2.1rem; color: var(--gold); text-align: center; }
93
.tagline, .hint, small { color: var(--muted); }
94
.tagline { text-align: center; margin: 0 0 1.2rem; }
95
.hint, small { font-size: 0.92rem; }
96
.error, .notice {
97
padding: 10px 14px;
98
border-radius: 10px;
99
margin: 12px 0;
100
}
101
.error { background: rgba(80,16,24,0.85); border: 1px solid #e88; color: #ffd6d6; }
102
.notice { background: rgba(40,36,16,0.85); border: 1px solid var(--gold-dim); }
103
.mono { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; letter-spacing: 0.08em; }
104
#app { max-width: 720px; margin: 0 auto; padding: 8px 16px 96px; }
105
.screen { animation: fade 0.2s ease; }
106
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
107
[hidden] { display: none !important; }
108
109
.menu-account { text-align: center; margin: 1rem 0; }
110
.menu-account a { color: var(--gold); }
111
.menu-account a.button { color: #1a1404; }
112
#menu-guest { display: flex; flex-direction: column; align-items: center; gap: 10px; }
113
#menu-local-login { display: block; max-width: 36rem; line-height: 1.6; }
114
.avatar-sm, .avatar {
115
border-radius: 50%;
116
object-fit: cover;
117
background: var(--bg-3);
118
vertical-align: middle;
119
}
120
.avatar-sm { width: 32px; height: 32px; margin-right: 6px; }
121
#menu-actions { display: flex; flex-direction: column; gap: 12px; margin: 1.4rem 0; }
122
.join-form { display: flex; gap: 8px; }
123
.join-form input { flex: 1; text-transform: uppercase; letter-spacing: 0.12em; text-align: center; }
124
125
.games-list, .player-list, .cf-ranges, #jury-list { list-style: none; padding: 0; margin: 0; }
126
.games-list li, .player-list li, .game-card {
127
display: flex; align-items: center; gap: 12px;
128
background: var(--bg-2);
129
border: 1px solid var(--line);
130
border-radius: var(--radius);
131
padding: 10px 12px;
132
margin: 8px 0;
133
min-height: var(--hit);
134
}
135
.games-list button { margin-left: auto; }
136
.player-dot {
137
width: 14px; height: 14px; border-radius: 50%;
138
flex-shrink: 0;
139
box-shadow: 0 0 0 2px #0006;
140
}
141
.invite-row { display: flex; gap: 8px; margin: 8px 0 16px; flex-wrap: wrap; }
142
.invite-row input { flex: 1; min-width: 0; font-size: 0.82rem; letter-spacing: 0; }
143
.actions { display: flex; flex-direction: column; gap: 10px; margin: 1.2rem 0; }
144
145
.toggle {
146
display: flex; gap: 12px; align-items: flex-start;
147
padding: 12px 0;
148
cursor: pointer;
149
}
150
.toggle input[type="checkbox"] {
151
appearance: none;
152
width: 48px; height: 28px; min-height: 28px;
153
border-radius: 14px;
154
background: #2a3148;
155
border: 1px solid var(--line);
156
position: relative;
157
flex-shrink: 0;
158
margin-top: 2px;
159
}
160
.toggle input[type="checkbox"]::after {
161
content: "";
162
position: absolute; top: 2px; left: 2px;
163
width: 22px; height: 22px; border-radius: 50%;
164
background: #c8cde0;
165
transition: transform 0.15s ease;
166
}
167
.toggle input[type="checkbox"]:checked { background: var(--gold-dim); }
168
.toggle input[type="checkbox"]:checked::after { transform: translateX(20px); background: #fff8e0; }
169
.toggle small { display: block; margin-top: 4px; }
170
.field { margin: 0 0 12px 60px; }
171
.field input[type="number"] { max-width: 6rem; }
172
173
/* Cease-fire clock */
174
.cf-clock { display: flex; justify-content: center; margin: 12px 0; touch-action: none; }
175
.cf-clock svg { width: min(86vw, 320px); height: auto; touch-action: none; user-select: none; }
176
.cf-ranges li {
177
display: flex; gap: 8px; align-items: center;
178
padding: 8px 0;
179
}
180
.cf-ranges input[type="time"] { max-width: 8rem; min-height: 40px; }
181
182
/* Top bar / countdowns */
183
#top-bar {
184
position: sticky; top: 0; z-index: 8;
185
background: linear-gradient(180deg, #0c1020 70%, #0c102000);
186
padding: 4px 0 12px;
187
text-align: center;
188
}
189
#top-title { font-weight: 700; color: var(--gold); letter-spacing: 0.04em; }
190
.countdown { margin: 4px 0; }
191
.cd-label { display: block; font-size: 0.78rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; }
192
.cd-hms {
193
font-variant-numeric: tabular-nums;
194
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
195
font-size: 1.85rem;
196
font-weight: 700;
197
letter-spacing: 0.06em;
198
color: var(--gold);
199
}
200
#cf-countdown .cd-hms { color: #f0c0c0; font-size: 1.45rem; }
201
#cf-countdown.active .cd-hms { color: var(--danger); }
202
#top-meta { font-size: 0.9rem; color: var(--muted); min-height: 1.3em; }
203
#shrink-banner { color: #ffcc77; margin-left: 8px; }
204
205
#game-hud {
206
display: flex; align-items: center; gap: 8px;
207
flex-wrap: wrap;
208
margin-bottom: 8px;
209
}
210
#you-stats { flex: 1; font-size: 0.95rem; }
211
#you-stats strong { color: var(--gold); }
212
.banner {
213
background: rgba(40, 36, 16, 0.9);
214
border: 1px solid var(--gold-dim);
215
border-radius: 10px;
216
padding: 8px 12px;
217
text-align: center;
218
}
219
220
/* Board */
221
#board-wrap {
222
display: flex; justify-content: center;
223
margin: 8px 0 16px;
224
touch-action: none;
225
}
226
#board {
227
display: grid;
228
gap: 3px;
229
width: min(96vw, 560px, calc(100dvh - 290px));
230
aspect-ratio: 1;
231
grid-template-rows: repeat(var(--n, 6), 1fr);
232
touch-action: none;
233
user-select: none;
234
-webkit-user-select: none;
235
}
236
.cell {
237
position: relative;
238
background: #1a2140;
239
border-radius: 6px;
240
border: 1px solid #2a3358;
241
min-width: 0; min-height: 0;
242
width: auto;
243
height: auto;
244
padding: 0;
245
aspect-ratio: 1;
246
cursor: pointer;
247
display: flex; align-items: center; justify-content: center;
248
touch-action: none;
249
color: inherit;
250
}
251
button.cell {
252
min-height: 0;
253
min-width: 0;
254
padding: 0;
255
background: #1a2140;
256
border-radius: 6px;
257
font-weight: 400;
258
}
259
.cell.impassable { background: #0a0c14; border-color: #111; cursor: default; }
260
.cell.threat { box-shadow: inset 0 0 0 2px #e8a03a; background: #2a2210; }
261
.cell.move-target { box-shadow: inset 0 0 0 3px var(--ok); background: #163226; }
262
.cell.selected { box-shadow: inset 0 0 0 3px var(--gold); }
263
.cell.in-range { box-shadow: inset 0 0 0 2px #e85d5d88; }
264
.piece {
265
width: 82%;
266
height: 82%;
267
max-width: 82%;
268
max-height: 82%;
269
aspect-ratio: 1;
270
border-radius: 50%;
271
border: 3px solid var(--c, #fff);
272
box-shadow: 0 0 0 1px #0008, 0 2px 6px #0006;
273
object-fit: cover;
274
background: #222;
275
pointer-events: none;
276
flex-shrink: 0;
277
}
278
.piece.dead { filter: grayscale(1) brightness(0.7); opacity: 0.7; border-style: dashed; }
279
.avatar-wrap-fixed {
280
display: inline-flex;
281
flex-shrink: 0;
282
align-items: center;
283
justify-content: center;
284
width: var(--sz, 40px);
285
height: var(--sz, 40px);
286
}
287
.piece-fixed {
288
width: var(--sz, 40px) !important;
289
height: var(--sz, 40px) !important;
290
border-width: 2px;
291
font-size: calc(var(--sz, 40px) * 0.38);
292
}
293
.piece-initials {
294
display: flex; align-items: center; justify-content: center;
295
font-weight: 700; font-size: 0.7em; color: #fff;
296
}
297
298
/* Timeline */
299
#timeline {
300
position: sticky; bottom: 0;
301
display: flex; align-items: center; gap: 8px;
302
background: #0c1020ee;
303
padding: 8px 0 calc(8px + 48px); /* room for lang picker */
304
z-index: 7;
305
touch-action: none;
306
}
307
#tl-play, #tl-live { flex-shrink: 0; }
308
#tl-play { width: var(--hit); padding: 0; font-size: 1.1rem; }
309
#tl-track {
310
position: relative;
311
flex: 1;
312
height: 44px;
313
background: var(--bg-2);
314
border: 1px solid var(--line);
315
border-radius: 8px;
316
touch-action: none;
317
cursor: pointer;
318
}
319
#tl-ticks { position: absolute; inset: 0; pointer-events: none; }
320
.tl-tick {
321
position: absolute; top: 8px; bottom: 8px;
322
width: 2px; background: var(--gold);
323
transform: translateX(-1px);
324
}
325
#tl-head {
326
position: absolute; top: 4px; bottom: 4px;
327
width: 4px; background: #fff;
328
border-radius: 2px;
329
transform: translateX(-2px);
330
pointer-events: none;
331
box-shadow: 0 0 6px #fff8;
332
}
333
334
/* Jury */
335
#jury-panel {
336
background: var(--bg-2);
337
border: 1px solid var(--line);
338
border-radius: var(--radius);
339
padding: 12px;
340
margin: 8px 0 16px;
341
}
342
#jury-list li { display: flex; align-items: center; gap: 10px; padding: 6px 0; }
343
#jury-list button { margin-left: auto; }
344
345
/* Modal / sheet / settings */
346
.modal, .sheet, .settings-panel {
347
position: fixed; inset: 0;
348
background: #0008;
349
z-index: 20;
350
display: flex; align-items: flex-end; justify-content: center;
351
padding: 16px 16px var(--safe-b);
352
touch-action: none;
353
}
354
.modal { align-items: center; }
355
.modal-card, .sheet-card, .settings-panel {
356
background: var(--bg-2);
357
border: 1px solid var(--line);
358
border-radius: 16px;
359
padding: 20px 18px 16px;
360
width: min(100%, 440px);
361
max-height: min(88vh, 40rem);
362
overflow-y: auto;
363
-webkit-overflow-scrolling: touch;
364
touch-action: pan-y;
365
position: relative;
366
}
367
.settings-panel {
368
position: fixed; inset: auto 16px var(--safe-b) 16px;
369
margin: 0 auto;
370
display: flex; flex-direction: column; gap: 10px;
371
top: auto;
372
background: var(--bg-2);
373
}
374
.modal-close {
375
position: absolute; top: 8px; right: 8px;
376
background: transparent; color: var(--ink);
377
min-width: var(--hit); width: var(--hit);
378
}
379
.chat-log {
380
max-height: 40vh; overflow-y: auto;
381
touch-action: pan-y;
382
display: flex; flex-direction: column; gap: 8px;
383
margin: 8px 0;
384
}
385
.chat-bubble {
386
max-width: 85%;
387
padding: 8px 12px;
388
border-radius: 12px;
389
background: var(--bg-3);
390
}
391
.chat-bubble.mine { align-self: flex-end; background: #3a3420; }
392
.chat-compose { display: flex; gap: 8px; }
393
.opt-list { display: flex; flex-direction: column; gap: 8px; }
394
.opt-list button { width: 100%; }
395
396
/* Language picker — same pattern as Meteors */
397
.lang-picker {
398
position: fixed;
399
right: var(--safe-r);
400
bottom: var(--safe-b);
401
z-index: 15;
402
display: flex;
403
flex-direction: column-reverse;
404
align-items: flex-end;
405
gap: 8px;
406
}
407
.lang-current {
408
appearance: none;
409
border: 1px solid rgba(200, 210, 240, 0.35);
410
background: rgba(16, 20, 40, 0.92);
411
border-radius: 8px;
412
padding: 6px 7px;
413
cursor: pointer;
414
line-height: 0;
415
box-shadow: 0 4px 14px rgba(0,0,0,0.4);
416
min-width: 52px;
417
min-height: 40px;
418
color: inherit;
419
}
420
.lang-current img, .lang-option img {
421
display: block; width: 36px; height: 24px;
422
object-fit: cover; border-radius: 3px;
423
image-rendering: auto;
424
box-shadow: 0 0 0 1px rgba(0,0,0,0.35);
425
}
426
.lang-current:focus-visible, .lang-option:focus-visible,
427
.lang-current[aria-expanded="true"] { border-color: var(--gold); outline: none; }
428
.lang-list {
429
display: flex; flex-direction: column; gap: 4px;
430
background: rgba(16, 14, 30, 0.96);
431
border: 1px solid #5a5470;
432
border-radius: 12px;
433
padding: 8px;
434
max-height: min(70vh, 28rem);
435
overflow-y: auto;
436
-webkit-overflow-scrolling: touch;
437
touch-action: pan-y;
438
box-shadow: 0 12px 32px rgba(0,0,0,0.45);
439
min-width: 11.5rem;
440
}
441
.lang-list[hidden] { display: none !important; }
442
.lang-option {
443
appearance: none;
444
display: flex; align-items: center; gap: 10px;
445
width: 100%;
446
border: 1px solid transparent;
447
background: transparent;
448
color: var(--ink);
449
font: inherit; font-size: 0.95rem;
450
padding: 6px 8px;
451
border-radius: 8px;
452
cursor: pointer;
453
text-align: left;
454
min-height: 40px;
455
white-space: nowrap;
456
}
457
.lang-option.current { border-color: var(--gold); background: rgba(40, 32, 16, 0.7); }
458
459
@media (min-width: 700px) {
460
#app { padding-bottom: 80px; }
461
#menu-actions { flex-direction: row; align-items: stretch; }
462
.join-form { flex: 1; }
463
.actions { flex-direction: row; }
464
.modal { align-items: center; }
465
}
466
@media (prefers-reduced-motion: reduce) {
467
.screen { animation: none; }
468
.toggle input[type="checkbox"]::after { transition: none; }
469
}
470
471
/* Visibility options */
472
.vis-panel { margin: 16px 0 8px; }
473
.vis-panel h3 { font-size: 1.05rem; margin: 0 0 6px; }
474
.vis-field {
475
border: 1px solid var(--line);
476
border-radius: var(--radius);
477
padding: 8px 12px 10px;
478
margin: 10px 0;
479
background: var(--bg-2);
480
}
481
.vis-field legend {
482
font-weight: 650;
483
padding: 0 6px;
484
color: var(--ink);
485
}
486
.vis-opt {
487
display: flex;
488
align-items: center;
489
gap: 10px;
490
min-height: var(--hit);
491
padding: 4px 4px;
492
cursor: pointer;
493
border-radius: 8px;
494
-webkit-tap-highlight-color: transparent;
495
}
496
.vis-opt:hover, .vis-opt:focus-within { background: #ffffff0c; }
497
.vis-opt input[type="radio"] {
498
width: 22px;
499
height: 22px;
500
accent-color: var(--gold);
501
flex-shrink: 0;
502
margin: 0;
503
}
504
.vis-opt input:disabled { cursor: not-allowed; }
505
506
/* Board effects (replay arrows / pulses) */
507
#board-wrap { position: relative; }
508
#board { position: relative; z-index: 1; overflow: visible; }
509
.cell { overflow: visible; }
510
.board-fx {
511
position: absolute;
512
inset: 0;
513
width: 100%;
514
height: 100%;
515
pointer-events: none;
516
z-index: 4;
517
overflow: visible;
518
}
519
.piece.moving {
520
position: relative;
521
z-index: 5;
522
will-change: transform;
523
}
524
.piece.range-pulse {
525
animation: range-pulse 0.55s ease-out;
526
}
527
@keyframes range-pulse {
528
0% { box-shadow: 0 0 0 0 rgba(232, 197, 71, 0.95), 0 0 0 1px #0008, 0 2px 6px #0006; }
529
60% { box-shadow: 0 0 0 18px rgba(232, 197, 71, 0), 0 0 0 1px #0008, 0 2px 6px #0006; }
530
100% { box-shadow: 0 0 0 0 rgba(232, 197, 71, 0), 0 0 0 1px #0008, 0 2px 6px #0006; }
531
}
532
.fx-float {
533
position: absolute;
534
z-index: 6;
535
pointer-events: none;
536
font-weight: 800;
537
font-size: 1.25rem;
538
font-variant-numeric: tabular-nums;
539
color: #4ecb8d;
540
text-shadow: 0 1px 4px #000c;
541
transform: translate(-50%, -50%);
542
animation: fx-rise 0.55s ease-out forwards;
543
}
544
@keyframes fx-rise {
545
from { opacity: 1; transform: translate(-50%, -40%) scale(1); }
546
to { opacity: 0.15; transform: translate(-50%, -140%) scale(1.25); }
547
}
548
549
/* Timeline: large touch target, ticks aligned with playhead (idx / n) */
550
#timeline { touch-action: none; user-select: none; -webkit-user-select: none; }
551
#tl-track {
552
height: var(--hit);
553
min-height: var(--hit);
554
touch-action: none;
555
cursor: pointer;
556
}
557
558
#tl-back, #tl-fwd { width: var(--hit); padding: 0; font-size: 1.4rem; font-weight: 700; }
559
.ap-time-field { margin-left: 0; }
560
.ap-time-field input[type="time"] { max-width: 10rem; }
561
#ap-time-wrap.field { margin-left: 0; padding: 8px 0 12px; }
@@ -0,0 +1,561 @@1
:root {2
--bg: #0c1020;3
--bg-2: #151a2e;4
--bg-3: #1c2340;5
--gold: #e8c547;6
--gold-dim: #b8942e;7
--ink: #e8eaf2;8
--muted: #9aa3bd;9
--danger: #e85d5d;10
--ok: #4ecb8d;11
--cf: #c44b4b;12
--line: rgba(200, 210, 240, 0.18);13
--safe-b: max(12px, env(safe-area-inset-bottom, 0px));14
--safe-t: max(8px, env(safe-area-inset-top, 0px));15
--safe-r: max(8px, env(safe-area-inset-right, 0px));16
--safe-l: max(8px, env(safe-area-inset-left, 0px));17
--radius: 12px;18
--hit: 44px;19
--font: "Source Sans 3", "Segoe UI", "Noto Sans", "Hiragino Sans", "Noto Sans CJK JP", "Noto Sans CJK SC", "Noto Sans CJK KR", sans-serif;20
}21
* { box-sizing: border-box; }22
html, body {23
margin: 0; padding: 0;24
background: var(--bg);25
color: var(--ink);26
font-family: var(--font);27
font-size: 16px;28
line-height: 1.45;29
min-height: 100%;30
min-height: 100dvh;31
-webkit-text-size-adjust: 100%;32
touch-action: manipulation;33
}34
body { padding: var(--safe-t) var(--safe-r) var(--safe-b) var(--safe-l); }35
button, input, a.button {36
font: inherit;37
touch-action: manipulation;38
}39
button, a.button {40
appearance: none;41
display: inline-flex;42
align-items: center;43
justify-content: center;44
min-height: var(--hit);45
min-width: var(--hit);46
padding: 10px 18px;47
border: 0;48
border-radius: 10px;49
background: var(--gold);50
color: #1a1404;51
font-weight: 650;52
cursor: pointer;53
text-decoration: none;54
}55
button:disabled { opacity: 0.45; cursor: not-allowed; }56
button:focus-visible, a.button:focus-visible, input:focus-visible {57
outline: 2px solid var(--gold);58
outline-offset: 2px;59
}60
.btn-secondary, .btn-secondary:link {61
background: var(--bg-3);62
color: var(--ink);63
border: 1px solid var(--line);64
}65
.btn-danger { background: var(--danger); color: #fff; }66
.btn-danger-outline {67
background: transparent;68
color: var(--danger);69
border: 1px solid var(--danger);70
}71
.btn-back {72
background: transparent;73
color: var(--muted);74
border: 1px solid var(--line);75
min-width: auto;76
margin-bottom: 8px;77
}78
input[type="text"], input[type="number"], input[type="time"], textarea {79
background: var(--bg-2);80
color: var(--ink);81
border: 1px solid var(--line);82
border-radius: 10px;83
padding: 10px 12px;84
min-height: var(--hit);85
width: 100%;86
}87
.sr-only {88
position: absolute; width: 1px; height: 1px;89
padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0;90
}91
h1, h2 { font-weight: 700; letter-spacing: 0.01em; margin: 0 0 0.4em; }92
h1 { font-size: 2.1rem; color: var(--gold); text-align: center; }93
.tagline, .hint, small { color: var(--muted); }94
.tagline { text-align: center; margin: 0 0 1.2rem; }95
.hint, small { font-size: 0.92rem; }96
.error, .notice {97
padding: 10px 14px;98
border-radius: 10px;99
margin: 12px 0;100
}101
.error { background: rgba(80,16,24,0.85); border: 1px solid #e88; color: #ffd6d6; }102
.notice { background: rgba(40,36,16,0.85); border: 1px solid var(--gold-dim); }103
.mono { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; letter-spacing: 0.08em; }104
#app { max-width: 720px; margin: 0 auto; padding: 8px 16px 96px; }105
.screen { animation: fade 0.2s ease; }106
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }107
[hidden] { display: none !important; }108
109
.menu-account { text-align: center; margin: 1rem 0; }110
.menu-account a { color: var(--gold); }111
.menu-account a.button { color: #1a1404; }112
#menu-guest { display: flex; flex-direction: column; align-items: center; gap: 10px; }113
#menu-local-login { display: block; max-width: 36rem; line-height: 1.6; }114
.avatar-sm, .avatar {115
border-radius: 50%;116
object-fit: cover;117
background: var(--bg-3);118
vertical-align: middle;119
}120
.avatar-sm { width: 32px; height: 32px; margin-right: 6px; }121
#menu-actions { display: flex; flex-direction: column; gap: 12px; margin: 1.4rem 0; }122
.join-form { display: flex; gap: 8px; }123
.join-form input { flex: 1; text-transform: uppercase; letter-spacing: 0.12em; text-align: center; }124
125
.games-list, .player-list, .cf-ranges, #jury-list { list-style: none; padding: 0; margin: 0; }126
.games-list li, .player-list li, .game-card {127
display: flex; align-items: center; gap: 12px;128
background: var(--bg-2);129
border: 1px solid var(--line);130
border-radius: var(--radius);131
padding: 10px 12px;132
margin: 8px 0;133
min-height: var(--hit);134
}135
.games-list button { margin-left: auto; }136
.player-dot {137
width: 14px; height: 14px; border-radius: 50%;138
flex-shrink: 0;139
box-shadow: 0 0 0 2px #0006;140
}141
.invite-row { display: flex; gap: 8px; margin: 8px 0 16px; flex-wrap: wrap; }142
.invite-row input { flex: 1; min-width: 0; font-size: 0.82rem; letter-spacing: 0; }143
.actions { display: flex; flex-direction: column; gap: 10px; margin: 1.2rem 0; }144
145
.toggle {146
display: flex; gap: 12px; align-items: flex-start;147
padding: 12px 0;148
cursor: pointer;149
}150
.toggle input[type="checkbox"] {151
appearance: none;152
width: 48px; height: 28px; min-height: 28px;153
border-radius: 14px;154
background: #2a3148;155
border: 1px solid var(--line);156
position: relative;157
flex-shrink: 0;158
margin-top: 2px;159
}160
.toggle input[type="checkbox"]::after {161
content: "";162
position: absolute; top: 2px; left: 2px;163
width: 22px; height: 22px; border-radius: 50%;164
background: #c8cde0;165
transition: transform 0.15s ease;166
}167
.toggle input[type="checkbox"]:checked { background: var(--gold-dim); }168
.toggle input[type="checkbox"]:checked::after { transform: translateX(20px); background: #fff8e0; }169
.toggle small { display: block; margin-top: 4px; }170
.field { margin: 0 0 12px 60px; }171
.field input[type="number"] { max-width: 6rem; }172
173
/* Cease-fire clock */174
.cf-clock { display: flex; justify-content: center; margin: 12px 0; touch-action: none; }175
.cf-clock svg { width: min(86vw, 320px); height: auto; touch-action: none; user-select: none; }176
.cf-ranges li {177
display: flex; gap: 8px; align-items: center;178
padding: 8px 0;179
}180
.cf-ranges input[type="time"] { max-width: 8rem; min-height: 40px; }181
182
/* Top bar / countdowns */183
#top-bar {184
position: sticky; top: 0; z-index: 8;185
background: linear-gradient(180deg, #0c1020 70%, #0c102000);186
padding: 4px 0 12px;187
text-align: center;188
}189
#top-title { font-weight: 700; color: var(--gold); letter-spacing: 0.04em; }190
.countdown { margin: 4px 0; }191
.cd-label { display: block; font-size: 0.78rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; }192
.cd-hms {193
font-variant-numeric: tabular-nums;194
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;195
font-size: 1.85rem;196
font-weight: 700;197
letter-spacing: 0.06em;198
color: var(--gold);199
}200
#cf-countdown .cd-hms { color: #f0c0c0; font-size: 1.45rem; }201
#cf-countdown.active .cd-hms { color: var(--danger); }202
#top-meta { font-size: 0.9rem; color: var(--muted); min-height: 1.3em; }203
#shrink-banner { color: #ffcc77; margin-left: 8px; }204
205
#game-hud {206
display: flex; align-items: center; gap: 8px;207
flex-wrap: wrap;208
margin-bottom: 8px;209
}210
#you-stats { flex: 1; font-size: 0.95rem; }211
#you-stats strong { color: var(--gold); }212
.banner {213
background: rgba(40, 36, 16, 0.9);214
border: 1px solid var(--gold-dim);215
border-radius: 10px;216
padding: 8px 12px;217
text-align: center;218
}219
220
/* Board */221
#board-wrap {222
display: flex; justify-content: center;223
margin: 8px 0 16px;224
touch-action: none;225
}226
#board {227
display: grid;228
gap: 3px;229
width: min(96vw, 560px, calc(100dvh - 290px));230
aspect-ratio: 1;231
grid-template-rows: repeat(var(--n, 6), 1fr);232
touch-action: none;233
user-select: none;234
-webkit-user-select: none;235
}236
.cell {237
position: relative;238
background: #1a2140;239
border-radius: 6px;240
border: 1px solid #2a3358;241
min-width: 0; min-height: 0;242
width: auto;243
height: auto;244
padding: 0;245
aspect-ratio: 1;246
cursor: pointer;247
display: flex; align-items: center; justify-content: center;248
touch-action: none;249
color: inherit;250
}251
button.cell {252
min-height: 0;253
min-width: 0;254
padding: 0;255
background: #1a2140;256
border-radius: 6px;257
font-weight: 400;258
}259
.cell.impassable { background: #0a0c14; border-color: #111; cursor: default; }260
.cell.threat { box-shadow: inset 0 0 0 2px #e8a03a; background: #2a2210; }261
.cell.move-target { box-shadow: inset 0 0 0 3px var(--ok); background: #163226; }262
.cell.selected { box-shadow: inset 0 0 0 3px var(--gold); }263
.cell.in-range { box-shadow: inset 0 0 0 2px #e85d5d88; }264
.piece {265
width: 82%;266
height: 82%;267
max-width: 82%;268
max-height: 82%;269
aspect-ratio: 1;270
border-radius: 50%;271
border: 3px solid var(--c, #fff);272
box-shadow: 0 0 0 1px #0008, 0 2px 6px #0006;273
object-fit: cover;274
background: #222;275
pointer-events: none;276
flex-shrink: 0;277
}278
.piece.dead { filter: grayscale(1) brightness(0.7); opacity: 0.7; border-style: dashed; }279
.avatar-wrap-fixed {280
display: inline-flex;281
flex-shrink: 0;282
align-items: center;283
justify-content: center;284
width: var(--sz, 40px);285
height: var(--sz, 40px);286
}287
.piece-fixed {288
width: var(--sz, 40px) !important;289
height: var(--sz, 40px) !important;290
border-width: 2px;291
font-size: calc(var(--sz, 40px) * 0.38);292
}293
.piece-initials {294
display: flex; align-items: center; justify-content: center;295
font-weight: 700; font-size: 0.7em; color: #fff;296
}297
298
/* Timeline */299
#timeline {300
position: sticky; bottom: 0;301
display: flex; align-items: center; gap: 8px;302
background: #0c1020ee;303
padding: 8px 0 calc(8px + 48px); /* room for lang picker */304
z-index: 7;305
touch-action: none;306
}307
#tl-play, #tl-live { flex-shrink: 0; }308
#tl-play { width: var(--hit); padding: 0; font-size: 1.1rem; }309
#tl-track {310
position: relative;311
flex: 1;312
height: 44px;313
background: var(--bg-2);314
border: 1px solid var(--line);315
border-radius: 8px;316
touch-action: none;317
cursor: pointer;318
}319
#tl-ticks { position: absolute; inset: 0; pointer-events: none; }320
.tl-tick {321
position: absolute; top: 8px; bottom: 8px;322
width: 2px; background: var(--gold);323
transform: translateX(-1px);324
}325
#tl-head {326
position: absolute; top: 4px; bottom: 4px;327
width: 4px; background: #fff;328
border-radius: 2px;329
transform: translateX(-2px);330
pointer-events: none;331
box-shadow: 0 0 6px #fff8;332
}333
334
/* Jury */335
#jury-panel {336
background: var(--bg-2);337
border: 1px solid var(--line);338
border-radius: var(--radius);339
padding: 12px;340
margin: 8px 0 16px;341
}342
#jury-list li { display: flex; align-items: center; gap: 10px; padding: 6px 0; }343
#jury-list button { margin-left: auto; }344
345
/* Modal / sheet / settings */346
.modal, .sheet, .settings-panel {347
position: fixed; inset: 0;348
background: #0008;349
z-index: 20;350
display: flex; align-items: flex-end; justify-content: center;351
padding: 16px 16px var(--safe-b);352
touch-action: none;353
}354
.modal { align-items: center; }355
.modal-card, .sheet-card, .settings-panel {356
background: var(--bg-2);357
border: 1px solid var(--line);358
border-radius: 16px;359
padding: 20px 18px 16px;360
width: min(100%, 440px);361
max-height: min(88vh, 40rem);362
overflow-y: auto;363
-webkit-overflow-scrolling: touch;364
touch-action: pan-y;365
position: relative;366
}367
.settings-panel {368
position: fixed; inset: auto 16px var(--safe-b) 16px;369
margin: 0 auto;370
display: flex; flex-direction: column; gap: 10px;371
top: auto;372
background: var(--bg-2);373
}374
.modal-close {375
position: absolute; top: 8px; right: 8px;376
background: transparent; color: var(--ink);377
min-width: var(--hit); width: var(--hit);378
}379
.chat-log {380
max-height: 40vh; overflow-y: auto;381
touch-action: pan-y;382
display: flex; flex-direction: column; gap: 8px;383
margin: 8px 0;384
}385
.chat-bubble {386
max-width: 85%;387
padding: 8px 12px;388
border-radius: 12px;389
background: var(--bg-3);390
}391
.chat-bubble.mine { align-self: flex-end; background: #3a3420; }392
.chat-compose { display: flex; gap: 8px; }393
.opt-list { display: flex; flex-direction: column; gap: 8px; }394
.opt-list button { width: 100%; }395
396
/* Language picker — same pattern as Meteors */397
.lang-picker {398
position: fixed;399
right: var(--safe-r);400
bottom: var(--safe-b);401
z-index: 15;402
display: flex;403
flex-direction: column-reverse;404
align-items: flex-end;405
gap: 8px;406
}407
.lang-current {408
appearance: none;409
border: 1px solid rgba(200, 210, 240, 0.35);410
background: rgba(16, 20, 40, 0.92);411
border-radius: 8px;412
padding: 6px 7px;413
cursor: pointer;414
line-height: 0;415
box-shadow: 0 4px 14px rgba(0,0,0,0.4);416
min-width: 52px;417
min-height: 40px;418
color: inherit;419
}420
.lang-current img, .lang-option img {421
display: block; width: 36px; height: 24px;422
object-fit: cover; border-radius: 3px;423
image-rendering: auto;424
box-shadow: 0 0 0 1px rgba(0,0,0,0.35);425
}426
.lang-current:focus-visible, .lang-option:focus-visible,427
.lang-current[aria-expanded="true"] { border-color: var(--gold); outline: none; }428
.lang-list {429
display: flex; flex-direction: column; gap: 4px;430
background: rgba(16, 14, 30, 0.96);431
border: 1px solid #5a5470;432
border-radius: 12px;433
padding: 8px;434
max-height: min(70vh, 28rem);435
overflow-y: auto;436
-webkit-overflow-scrolling: touch;437
touch-action: pan-y;438
box-shadow: 0 12px 32px rgba(0,0,0,0.45);439
min-width: 11.5rem;440
}441
.lang-list[hidden] { display: none !important; }442
.lang-option {443
appearance: none;444
display: flex; align-items: center; gap: 10px;445
width: 100%;446
border: 1px solid transparent;447
background: transparent;448
color: var(--ink);449
font: inherit; font-size: 0.95rem;450
padding: 6px 8px;451
border-radius: 8px;452
cursor: pointer;453
text-align: left;454
min-height: 40px;455
white-space: nowrap;456
}457
.lang-option.current { border-color: var(--gold); background: rgba(40, 32, 16, 0.7); }458
459
@media (min-width: 700px) {460
#app { padding-bottom: 80px; }461
#menu-actions { flex-direction: row; align-items: stretch; }462
.join-form { flex: 1; }463
.actions { flex-direction: row; }464
.modal { align-items: center; }465
}466
@media (prefers-reduced-motion: reduce) {467
.screen { animation: none; }468
.toggle input[type="checkbox"]::after { transition: none; }469
}470
471
/* Visibility options */472
.vis-panel { margin: 16px 0 8px; }473
.vis-panel h3 { font-size: 1.05rem; margin: 0 0 6px; }474
.vis-field {475
border: 1px solid var(--line);476
border-radius: var(--radius);477
padding: 8px 12px 10px;478
margin: 10px 0;479
background: var(--bg-2);480
}481
.vis-field legend {482
font-weight: 650;483
padding: 0 6px;484
color: var(--ink);485
}486
.vis-opt {487
display: flex;488
align-items: center;489
gap: 10px;490
min-height: var(--hit);491
padding: 4px 4px;492
cursor: pointer;493
border-radius: 8px;494
-webkit-tap-highlight-color: transparent;495
}496
.vis-opt:hover, .vis-opt:focus-within { background: #ffffff0c; }497
.vis-opt input[type="radio"] {498
width: 22px;499
height: 22px;500
accent-color: var(--gold);501
flex-shrink: 0;502
margin: 0;503
}504
.vis-opt input:disabled { cursor: not-allowed; }505
506
/* Board effects (replay arrows / pulses) */507
#board-wrap { position: relative; }508
#board { position: relative; z-index: 1; overflow: visible; }509
.cell { overflow: visible; }510
.board-fx {511
position: absolute;512
inset: 0;513
width: 100%;514
height: 100%;515
pointer-events: none;516
z-index: 4;517
overflow: visible;518
}519
.piece.moving {520
position: relative;521
z-index: 5;522
will-change: transform;523
}524
.piece.range-pulse {525
animation: range-pulse 0.55s ease-out;526
}527
@keyframes range-pulse {528
0% { box-shadow: 0 0 0 0 rgba(232, 197, 71, 0.95), 0 0 0 1px #0008, 0 2px 6px #0006; }529
60% { box-shadow: 0 0 0 18px rgba(232, 197, 71, 0), 0 0 0 1px #0008, 0 2px 6px #0006; }530
100% { box-shadow: 0 0 0 0 rgba(232, 197, 71, 0), 0 0 0 1px #0008, 0 2px 6px #0006; }531
}532
.fx-float {533
position: absolute;534
z-index: 6;535
pointer-events: none;536
font-weight: 800;537
font-size: 1.25rem;538
font-variant-numeric: tabular-nums;539
color: #4ecb8d;540
text-shadow: 0 1px 4px #000c;541
transform: translate(-50%, -50%);542
animation: fx-rise 0.55s ease-out forwards;543
}544
@keyframes fx-rise {545
from { opacity: 1; transform: translate(-50%, -40%) scale(1); }546
to { opacity: 0.15; transform: translate(-50%, -140%) scale(1.25); }547
}548
549
/* Timeline: large touch target, ticks aligned with playhead (idx / n) */550
#timeline { touch-action: none; user-select: none; -webkit-user-select: none; }551
#tl-track {552
height: var(--hit);553
min-height: var(--hit);554
touch-action: none;555
cursor: pointer;556
}557
558
#tl-back, #tl-fwd { width: var(--hit); padding: 0; font-size: 1.4rem; font-weight: 700; }559
.ap-time-field { margin-left: 0; }560
.ap-time-field input[type="time"] { max-width: 10rem; }561
#ap-time-wrap.field { margin-left: 0; padding: 8px 0 12px; }@@ -0,0 +1,274 @@
1
#!/usr/bin/env python3
2
"""FTP-upload of build/. Never --delete.
3
4
The path guard (deploy_guard) is the only hard abort: wrong target,
5
FTP root, missing allianties leaf. Extra files already on the remote are
6
logged and left alone. favicon.ico is never uploaded, so a host- or
7
Tim-provided icon is not overwritten.
8
"""
9
import os
10
import subprocess
11
import sys
12
import tempfile
13
from pathlib import Path
14
from urllib.parse import urlsplit
15
16
sys.path.insert(0, str(Path(__file__).resolve().parent))
17
from deploy_guard import DeployGuardError, project_dir # noqa: E402
18
19
ROOT = Path(__file__).resolve().parents[1]
20
21
# Files this project publishes. Used only to label remote leftovers in the
22
# log; foreign names no longer abort the deploy (we never --delete).
23
OURS = {
24
'index.html', 'game.js', 'style.css', 'images',
25
'api.php', 'auth.php', 'callback.php', 'logout.php', '.htaccess',
26
'lib', 'data', 'router.php',
27
'.', '..',
28
}
29
30
# Never upload this name: the remote icon may belong to Tim or the host.
31
LEAVE_ON_REMOTE = ('favicon.ico',)
32
33
# OAuth file written from CI secrets. Names match BlueGit project secrets.
34
# The group and sibling repos (verhalenboek, microchess, …) have no
35
# auth.timfalken.com client secret — only FTP credentials — so this is a
36
# allianties project secret. client_id is public and optional to override.
37
AUTH_SECRET_ENV = 'auth_client_secret'
38
AUTH_CLIENT_ID_ENV = 'auth_client_id'
39
DEFAULT_AUTH_URL = 'https://auth.timfalken.com'
40
DEFAULT_BASE_URL = 'https://projects.timfalken.com/allianties'
41
DEFAULT_CLIENT_ID = 'projects.timfalken.com'
42
43
44
def quoted(value):
45
if any(c in value for c in '\r\n\x00'):
46
raise ValueError('Deployment variables must not contain line breaks or NUL bytes.')
47
return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'
48
49
50
def php_single_quoted(value):
51
"""A PHP single-quoted string. Raises if the value has a NUL or newline."""
52
if any(c in value for c in '\r\n\x00'):
53
raise ValueError('auth config values must not contain line breaks or NUL bytes.')
54
return "'" + value.replace('\\', '\\\\').replace("'", "\\'") + "'"
55
56
57
def auth_secret(environ):
58
"""Return the stripped secret, or '' if unset/empty. Never print this."""
59
raw = environ.get(AUTH_SECRET_ENV)
60
if raw is None:
61
return ''
62
return str(raw).strip()
63
64
65
def auth_config_php(environ):
66
"""PHP source for data/config.php, or None if the secret is empty.
67
68
The secret itself is only placed inside a single-quoted PHP string.
69
Callers must not log the return value.
70
"""
71
secret = auth_secret(environ)
72
if not secret:
73
return None
74
client_id = (environ.get(AUTH_CLIENT_ID_ENV) or '').strip() or DEFAULT_CLIENT_ID
75
auth_url = DEFAULT_AUTH_URL
76
base_url = DEFAULT_BASE_URL
77
# Built as a list so the secret is only interpolated via php_single_quoted.
78
return (
79
'<?php\n'
80
'// Written by CI from the auth_client_secret project secret. Not in git.\n'
81
'return [\n'
82
f" 'auth_url' => {php_single_quoted(auth_url)},\n"
83
f" 'base_url' => {php_single_quoted(base_url)},\n"
84
f" 'client_id' => {php_single_quoted(client_id)},\n"
85
f" 'client_secret' => {php_single_quoted(secret)},\n"
86
'];\n'
87
)
88
89
90
def host_url(environ):
91
for key in ['timftphost', 'timftpuser', 'timftppassword']:
92
if not environ.get(key):
93
raise ValueError(f'CI variable {key} is not set.')
94
host = environ['timftphost']
95
if '://' not in host:
96
host = 'ftp://' + host
97
parsed = urlsplit(host)
98
if parsed.scheme not in ['ftp', 'ftps', 'sftp'] or not parsed.hostname:
99
raise ValueError('timftphost must be an FTP, FTPS or SFTP host URL.')
100
if parsed.username or parsed.password or parsed.query or parsed.fragment:
101
raise ValueError('Keep login credentials in timftpuser/timftppassword; use a plain host URL.')
102
return host
103
104
105
def lftp_preamble(environ, host):
106
return [
107
'set cmd:fail-exit yes',
108
'set net:timeout 20',
109
'set net:max-retries 2',
110
'set net:reconnect-interval-base 3',
111
'set ssl:verify-certificate no',
112
'set ftp:list-options -a',
113
'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
114
'set sftp:auto-confirm yes',
115
'set xfer:use-temp-file yes',
116
f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',
117
]
118
119
120
def run_lftp(commands, environ):
121
subprocess.run(
122
['lftp', '--norc'],
123
input='\n'.join(commands) + '\n',
124
text=True,
125
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},
126
check=True,
127
)
128
129
130
def list_remote(environ, target):
131
"""Return (exists, names). exists=False means the folder is not there yet."""
132
host = host_url(environ)
133
# Probe with cls; a missing folder makes `cd` fail.
134
probe = lftp_preamble(environ, host) + [
135
'set cmd:fail-exit no',
136
f'cd {quoted(target)} && cls -1 && echo __ALLIANTIES_DIR_OK__ || echo __ALLIANTIES_DIR_MISSING__',
137
'bye',
138
]
139
result = subprocess.run(
140
['lftp', '--norc'],
141
input='\n'.join(probe) + '\n',
142
text=True,
143
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},
144
check=True,
145
capture_output=True,
146
)
147
out = (result.stdout or '') + (result.stderr or '')
148
if '__ALLIANTIES_DIR_MISSING__' in out and '__ALLIANTIES_DIR_OK__' not in out:
149
return False, []
150
names = []
151
for line in out.splitlines():
152
name = line.strip().rstrip('/')
153
if not name or name.startswith('__ALLIANTIES_') or name.startswith('lftp'):
154
continue
155
# lftp may print status; keep path-like tokens
156
if ' ' in name and not name.startswith('.'):
157
# long listing leftover; take the last field
158
name = name.split()[-1]
159
names.append(posix_basename(name))
160
return True, names
161
162
163
def posix_basename(name):
164
return name.rstrip('/').split('/')[-1]
165
166
167
def assert_safe_target(exists, names):
168
"""Path safety lives in deploy_guard.project_dir. Remote leftovers are fine."""
169
if not exists:
170
print('Remote allianties folder does not exist yet; it will be created.')
171
return
172
foreign = []
173
for name in names:
174
leaf = posix_basename(name)
175
if leaf in OURS or leaf == '' or leaf in LEAVE_ON_REMOTE:
176
continue
177
foreign.append(leaf)
178
if foreign:
179
print(
180
'Opmerking: de remote map bevat ook bestanden die niet bij deze '
181
'deploy horen: '
182
+ ', '.join(sorted(set(foreign))[:12])
183
+ '. Die blijven staan (geen --delete) en worden niet aangeraakt.'
184
)
185
reserved = [posix_basename(n) for n in names if posix_basename(n) in LEAVE_ON_REMOTE]
186
if reserved:
187
print(
188
'Opmerking: '
189
+ ', '.join(sorted(set(reserved)))
190
+ ' blijft ongemoeid; we uploaden dat bestand niet.'
191
)
192
if names:
193
print('Remote allianties folder already holds files; updating our own.')
194
else:
195
print('Remote allianties folder is empty; deploying.')
196
197
198
def deploy_commands(environ, target, webroot, auth_config_path=None):
199
host = host_url(environ)
200
commands = lftp_preamble(environ, host) + [
201
f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
202
f'cd {quoted(target)}',
203
# GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).
204
# Never mirror data/: that folder holds the sqlite database and
205
# sessions. We only ensure data/.htaccess afterwards, and optionally
206
# write data/config.php from auth_client_secret (never from the
207
# build tree, which must not contain a secret).
208
'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
209
'--exclude-glob ".git/" --exclude-glob ".git/**" '
210
'--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
211
'--exclude-glob "favicon.ico" --exclude-glob "**/favicon.ico" '
212
'--exclude-glob "router.php" '
213
'--exclude-glob "data/" --exclude-glob "data/**" '
214
'--exclude-glob "**/config.php" --exclude-glob "**/*.sqlite" '
215
f'{quoted(str(webroot))} .',
216
# Ensure the deny-all htaccess exists; do not delete any data file.
217
'mkdir -p data || echo "data exists"',
218
f'put {quoted(str(webroot / "data" / ".htaccess"))} -o data/.htaccess',
219
]
220
if auth_config_path:
221
# The lftp script only has the local path, never the secret.
222
commands.append(
223
f'put {quoted(str(auth_config_path))} -o data/config.php'
224
)
225
commands.append('bye')
226
return commands
227
228
229
def main():
230
environ = os.environ
231
try:
232
target = project_dir(environ)
233
webroot = ROOT / 'build'
234
if not (webroot / 'index.html').is_file() or not (webroot / 'game.js').is_file():
235
raise ValueError('build/ is incomplete (need index.html and game.js).')
236
if not (webroot / 'style.css').is_file() or not (webroot / 'images').is_dir():
237
raise ValueError('build/ is incomplete (need style.css and images/).')
238
exists, names = list_remote(environ, target)
239
assert_safe_target(exists, names)
240
php = auth_config_php(environ)
241
auth_path = None
242
tmpdir = None
243
try:
244
if php is not None:
245
tmpdir = tempfile.TemporaryDirectory(prefix='allianties-auth-')
246
auth_path = Path(tmpdir.name) / 'config.php'
247
# 0o600: the secret lives in this file only until lftp puts it.
248
fd = os.open(auth_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
249
try:
250
os.write(fd, php.encode('utf-8'))
251
finally:
252
os.close(fd)
253
print('Writing data/config.php from CI secret auth_client_secret.')
254
else:
255
print(
256
'CI secret auth_client_secret is empty or unset; '
257
'leaving data/config.php alone.'
258
)
259
run_lftp(
260
deploy_commands(environ, target, webroot, auth_config_path=auth_path),
261
environ,
262
)
263
finally:
264
if tmpdir is not None:
265
tmpdir.cleanup()
266
print('Deploy complete (no --delete).')
267
return 0
268
except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error:
269
print(str(error), file=sys.stderr)
270
return 1
271
272
273
if __name__ == '__main__':
274
sys.exit(main())
@@ -0,0 +1,274 @@1
#!/usr/bin/env python32
"""FTP-upload of build/. Never --delete.3
4
The path guard (deploy_guard) is the only hard abort: wrong target,5
FTP root, missing allianties leaf. Extra files already on the remote are6
logged and left alone. favicon.ico is never uploaded, so a host- or7
Tim-provided icon is not overwritten.8
"""9
import os10
import subprocess11
import sys12
import tempfile13
from pathlib import Path14
from urllib.parse import urlsplit15
16
sys.path.insert(0, str(Path(__file__).resolve().parent))17
from deploy_guard import DeployGuardError, project_dir # noqa: E40218
19
ROOT = Path(__file__).resolve().parents[1]20
21
# Files this project publishes. Used only to label remote leftovers in the22
# log; foreign names no longer abort the deploy (we never --delete).23
OURS = {24
'index.html', 'game.js', 'style.css', 'images',25
'api.php', 'auth.php', 'callback.php', 'logout.php', '.htaccess',26
'lib', 'data', 'router.php',27
'.', '..',28
}29
30
# Never upload this name: the remote icon may belong to Tim or the host.31
LEAVE_ON_REMOTE = ('favicon.ico',)32
33
# OAuth file written from CI secrets. Names match BlueGit project secrets.34
# The group and sibling repos (verhalenboek, microchess, …) have no35
# auth.timfalken.com client secret — only FTP credentials — so this is a36
# allianties project secret. client_id is public and optional to override.37
AUTH_SECRET_ENV = 'auth_client_secret'38
AUTH_CLIENT_ID_ENV = 'auth_client_id'39
DEFAULT_AUTH_URL = 'https://auth.timfalken.com'40
DEFAULT_BASE_URL = 'https://projects.timfalken.com/allianties'41
DEFAULT_CLIENT_ID = 'projects.timfalken.com'42
43
44
def quoted(value):45
if any(c in value for c in '\r\n\x00'):46
raise ValueError('Deployment variables must not contain line breaks or NUL bytes.')47
return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'48
49
50
def php_single_quoted(value):51
"""A PHP single-quoted string. Raises if the value has a NUL or newline."""52
if any(c in value for c in '\r\n\x00'):53
raise ValueError('auth config values must not contain line breaks or NUL bytes.')54
return "'" + value.replace('\\', '\\\\').replace("'", "\\'") + "'"55
56
57
def auth_secret(environ):58
"""Return the stripped secret, or '' if unset/empty. Never print this."""59
raw = environ.get(AUTH_SECRET_ENV)60
if raw is None:61
return ''62
return str(raw).strip()63
64
65
def auth_config_php(environ):66
"""PHP source for data/config.php, or None if the secret is empty.67
68
The secret itself is only placed inside a single-quoted PHP string.69
Callers must not log the return value.70
"""71
secret = auth_secret(environ)72
if not secret:73
return None74
client_id = (environ.get(AUTH_CLIENT_ID_ENV) or '').strip() or DEFAULT_CLIENT_ID75
auth_url = DEFAULT_AUTH_URL76
base_url = DEFAULT_BASE_URL77
# Built as a list so the secret is only interpolated via php_single_quoted.78
return (79
'<?php\n'80
'// Written by CI from the auth_client_secret project secret. Not in git.\n'81
'return [\n'82
f" 'auth_url' => {php_single_quoted(auth_url)},\n"83
f" 'base_url' => {php_single_quoted(base_url)},\n"84
f" 'client_id' => {php_single_quoted(client_id)},\n"85
f" 'client_secret' => {php_single_quoted(secret)},\n"86
'];\n'87
)88
89
90
def host_url(environ):91
for key in ['timftphost', 'timftpuser', 'timftppassword']:92
if not environ.get(key):93
raise ValueError(f'CI variable {key} is not set.')94
host = environ['timftphost']95
if '://' not in host:96
host = 'ftp://' + host97
parsed = urlsplit(host)98
if parsed.scheme not in ['ftp', 'ftps', 'sftp'] or not parsed.hostname:99
raise ValueError('timftphost must be an FTP, FTPS or SFTP host URL.')100
if parsed.username or parsed.password or parsed.query or parsed.fragment:101
raise ValueError('Keep login credentials in timftpuser/timftppassword; use a plain host URL.')102
return host103
104
105
def lftp_preamble(environ, host):106
return [107
'set cmd:fail-exit yes',108
'set net:timeout 20',109
'set net:max-retries 2',110
'set net:reconnect-interval-base 3',111
'set ssl:verify-certificate no',112
'set ftp:list-options -a',113
'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',114
'set sftp:auto-confirm yes',115
'set xfer:use-temp-file yes',116
f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',117
]118
119
120
def run_lftp(commands, environ):121
subprocess.run(122
['lftp', '--norc'],123
input='\n'.join(commands) + '\n',124
text=True,125
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},126
check=True,127
)128
129
130
def list_remote(environ, target):131
"""Return (exists, names). exists=False means the folder is not there yet."""132
host = host_url(environ)133
# Probe with cls; a missing folder makes `cd` fail.134
probe = lftp_preamble(environ, host) + [135
'set cmd:fail-exit no',136
f'cd {quoted(target)} && cls -1 && echo __ALLIANTIES_DIR_OK__ || echo __ALLIANTIES_DIR_MISSING__',137
'bye',138
]139
result = subprocess.run(140
['lftp', '--norc'],141
input='\n'.join(probe) + '\n',142
text=True,143
env={**environ, 'LFTP_PASSWORD': environ['timftppassword']},144
check=True,145
capture_output=True,146
)147
out = (result.stdout or '') + (result.stderr or '')148
if '__ALLIANTIES_DIR_MISSING__' in out and '__ALLIANTIES_DIR_OK__' not in out:149
return False, []150
names = []151
for line in out.splitlines():152
name = line.strip().rstrip('/')153
if not name or name.startswith('__ALLIANTIES_') or name.startswith('lftp'):154
continue155
# lftp may print status; keep path-like tokens156
if ' ' in name and not name.startswith('.'):157
# long listing leftover; take the last field158
name = name.split()[-1]159
names.append(posix_basename(name))160
return True, names161
162
163
def posix_basename(name):164
return name.rstrip('/').split('/')[-1]165
166
167
def assert_safe_target(exists, names):168
"""Path safety lives in deploy_guard.project_dir. Remote leftovers are fine."""169
if not exists:170
print('Remote allianties folder does not exist yet; it will be created.')171
return172
foreign = []173
for name in names:174
leaf = posix_basename(name)175
if leaf in OURS or leaf == '' or leaf in LEAVE_ON_REMOTE:176
continue177
foreign.append(leaf)178
if foreign:179
print(180
'Opmerking: de remote map bevat ook bestanden die niet bij deze '181
'deploy horen: '182
+ ', '.join(sorted(set(foreign))[:12])183
+ '. Die blijven staan (geen --delete) en worden niet aangeraakt.'184
)185
reserved = [posix_basename(n) for n in names if posix_basename(n) in LEAVE_ON_REMOTE]186
if reserved:187
print(188
'Opmerking: '189
+ ', '.join(sorted(set(reserved)))190
+ ' blijft ongemoeid; we uploaden dat bestand niet.'191
)192
if names:193
print('Remote allianties folder already holds files; updating our own.')194
else:195
print('Remote allianties folder is empty; deploying.')196
197
198
def deploy_commands(environ, target, webroot, auth_config_path=None):199
host = host_url(environ)200
commands = lftp_preamble(environ, host) + [201
f'mkdir -p {quoted(target)} || echo "Using existing project directory"',202
f'cd {quoted(target)}',203
# GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).204
# Never mirror data/: that folder holds the sqlite database and205
# sessions. We only ensure data/.htaccess afterwards, and optionally206
# write data/config.php from auth_client_secret (never from the207
# build tree, which must not contain a secret).208
'mirror --reverse --no-perms --no-symlinks --max-errors=1 '209
'--exclude-glob ".git/" --exclude-glob ".git/**" '210
'--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '211
'--exclude-glob "favicon.ico" --exclude-glob "**/favicon.ico" '212
'--exclude-glob "router.php" '213
'--exclude-glob "data/" --exclude-glob "data/**" '214
'--exclude-glob "**/config.php" --exclude-glob "**/*.sqlite" '215
f'{quoted(str(webroot))} .',216
# Ensure the deny-all htaccess exists; do not delete any data file.217
'mkdir -p data || echo "data exists"',218
f'put {quoted(str(webroot / "data" / ".htaccess"))} -o data/.htaccess',219
]220
if auth_config_path:221
# The lftp script only has the local path, never the secret.222
commands.append(223
f'put {quoted(str(auth_config_path))} -o data/config.php'224
)225
commands.append('bye')226
return commands227
228
229
def main():230
environ = os.environ231
try:232
target = project_dir(environ)233
webroot = ROOT / 'build'234
if not (webroot / 'index.html').is_file() or not (webroot / 'game.js').is_file():235
raise ValueError('build/ is incomplete (need index.html and game.js).')236
if not (webroot / 'style.css').is_file() or not (webroot / 'images').is_dir():237
raise ValueError('build/ is incomplete (need style.css and images/).')238
exists, names = list_remote(environ, target)239
assert_safe_target(exists, names)240
php = auth_config_php(environ)241
auth_path = None242
tmpdir = None243
try:244
if php is not None:245
tmpdir = tempfile.TemporaryDirectory(prefix='allianties-auth-')246
auth_path = Path(tmpdir.name) / 'config.php'247
# 0o600: the secret lives in this file only until lftp puts it.248
fd = os.open(auth_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)249
try:250
os.write(fd, php.encode('utf-8'))251
finally:252
os.close(fd)253
print('Writing data/config.php from CI secret auth_client_secret.')254
else:255
print(256
'CI secret auth_client_secret is empty or unset; '257
'leaving data/config.php alone.'258
)259
run_lftp(260
deploy_commands(environ, target, webroot, auth_config_path=auth_path),261
environ,262
)263
finally:264
if tmpdir is not None:265
tmpdir.cleanup()266
print('Deploy complete (no --delete).')267
return 0268
except (ValueError, DeployGuardError, subprocess.CalledProcessError) as error:269
print(str(error), file=sys.stderr)270
return 1271
272
273
if __name__ == '__main__':274
sys.exit(main())@@ -0,0 +1,92 @@
1
#!/usr/bin/env python3
2
"""Deploy guard: expand $timftproot, refuse a deploy that would hit the FTP root."""
3
import posixpath
4
import re
5
import sys
6
7
ROOT_VAR = 'timftproot'
8
PROJECT_VAR = 'projectftp'
9
ALLOWED_LEAF = 'allianties'
10
11
12
class DeployGuardError(ValueError):
13
pass
14
15
16
def _expand(value, environ):
17
"""Expand $timftproot / ${timftproot} (BlueGit secrets do not)."""
18
root = environ.get(ROOT_VAR) or ''
19
return re.sub(r'\$\{?' + ROOT_VAR + r'\}?', lambda _m: root, value)
20
21
22
def _norm(path):
23
path = (path or '').strip()
24
if not path:
25
return ''
26
# Collapse duplicate slashes before and after normpath.
27
path = re.sub(r'/+', '/', path.replace('\\', '/'))
28
norm = posixpath.normpath(path)
29
return '/' if norm in ('/', '//', '.') else norm.rstrip('/') or '/'
30
31
32
def project_dir(environ):
33
raw = environ.get(PROJECT_VAR)
34
if raw is None:
35
raise DeployGuardError(
36
f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is niet gezet. '
37
f'Zet de projectmap als project-secret, bijvoorbeeld $timftproot/{ALLOWED_LEAF}.'
38
)
39
if any(c in raw for c in '\r\n\x00'):
40
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')
41
leftover_dollar = raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', '')
42
if '$' in leftover_dollar:
43
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een onbekende $-verwijzing.')
44
if (('$' + ROOT_VAR) in raw or ('${' + ROOT_VAR + '}') in raw) and not (environ.get(ROOT_VAR) or '').strip():
45
raise DeployGuardError(
46
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} verwijst naar {ROOT_VAR}, maar die is niet gezet.'
47
)
48
value = _expand(raw, environ).strip()
49
if not value:
50
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is leeg.')
51
parts = [p for p in value.replace('\\', '/').split('/') if p]
52
if '..' in parts:
53
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag geen ".." bevatten.')
54
if value.startswith('~'):
55
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag niet de thuismap (~) zijn.')
56
norm = _norm(value)
57
if norm in ('/', '.', ''):
58
raise DeployGuardError(
59
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} wijst naar de root ("/" of "."); '
60
'dat zou de hele website overschrijven.'
61
)
62
root = _norm(environ.get(ROOT_VAR) or '')
63
if root and norm == root:
64
raise DeployGuardError(
65
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} is gelijk aan {ROOT_VAR} (de FTP-root van de site); '
66
'dat zou de hele website overschrijven.'
67
)
68
if root and root not in ('/', '.') and norm.startswith('/') and not norm.startswith(root + '/'):
69
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} ligt niet onder {ROOT_VAR}.')
70
leaf = parts[-1].lower() if parts else ''
71
if leaf != ALLOWED_LEAF:
72
raise DeployGuardError(
73
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} moet op "{ALLOWED_LEAF}" eindigen (leaf={leaf!r}).'
74
)
75
return norm
76
77
78
def main(environ=None):
79
import os
80
try:
81
path = project_dir(os.environ if environ is None else environ)
82
except DeployGuardError as error:
83
print(str(error), file=sys.stderr)
84
return 1
85
print('Deploy guard: projectmap ok.')
86
# Path itself is not printed (secrets). Length only.
87
print('projectftp length=%d' % len(path))
88
return 0
89
90
91
if __name__ == '__main__':
92
sys.exit(main())
@@ -0,0 +1,92 @@1
#!/usr/bin/env python32
"""Deploy guard: expand $timftproot, refuse a deploy that would hit the FTP root."""3
import posixpath4
import re5
import sys6
7
ROOT_VAR = 'timftproot'8
PROJECT_VAR = 'projectftp'9
ALLOWED_LEAF = 'allianties'10
11
12
class DeployGuardError(ValueError):13
pass14
15
16
def _expand(value, environ):17
"""Expand $timftproot / ${timftproot} (BlueGit secrets do not)."""18
root = environ.get(ROOT_VAR) or ''19
return re.sub(r'\$\{?' + ROOT_VAR + r'\}?', lambda _m: root, value)20
21
22
def _norm(path):23
path = (path or '').strip()24
if not path:25
return ''26
# Collapse duplicate slashes before and after normpath.27
path = re.sub(r'/+', '/', path.replace('\\', '/'))28
norm = posixpath.normpath(path)29
return '/' if norm in ('/', '//', '.') else norm.rstrip('/') or '/'30
31
32
def project_dir(environ):33
raw = environ.get(PROJECT_VAR)34
if raw is None:35
raise DeployGuardError(36
f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is niet gezet. '37
f'Zet de projectmap als project-secret, bijvoorbeeld $timftproot/{ALLOWED_LEAF}.'38
)39
if any(c in raw for c in '\r\n\x00'):40
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een regeleinde of NUL-byte.')41
leftover_dollar = raw.replace('$' + ROOT_VAR, '').replace('${' + ROOT_VAR + '}', '')42
if '$' in leftover_dollar:43
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} bevat een onbekende $-verwijzing.')44
if (('$' + ROOT_VAR) in raw or ('${' + ROOT_VAR + '}') in raw) and not (environ.get(ROOT_VAR) or '').strip():45
raise DeployGuardError(46
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} verwijst naar {ROOT_VAR}, maar die is niet gezet.'47
)48
value = _expand(raw, environ).strip()49
if not value:50
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: CI-variabele {PROJECT_VAR} is leeg.')51
parts = [p for p in value.replace('\\', '/').split('/') if p]52
if '..' in parts:53
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag geen ".." bevatten.')54
if value.startswith('~'):55
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} mag niet de thuismap (~) zijn.')56
norm = _norm(value)57
if norm in ('/', '.', ''):58
raise DeployGuardError(59
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} wijst naar de root ("/" of "."); '60
'dat zou de hele website overschrijven.'61
)62
root = _norm(environ.get(ROOT_VAR) or '')63
if root and norm == root:64
raise DeployGuardError(65
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} is gelijk aan {ROOT_VAR} (de FTP-root van de site); '66
'dat zou de hele website overschrijven.'67
)68
if root and root not in ('/', '.') and norm.startswith('/') and not norm.startswith(root + '/'):69
raise DeployGuardError(f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} ligt niet onder {ROOT_VAR}.')70
leaf = parts[-1].lower() if parts else ''71
if leaf != ALLOWED_LEAF:72
raise DeployGuardError(73
f'DEPLOY GEBLOKKEERD: {PROJECT_VAR} moet op "{ALLOWED_LEAF}" eindigen (leaf={leaf!r}).'74
)75
return norm76
77
78
def main(environ=None):79
import os80
try:81
path = project_dir(os.environ if environ is None else environ)82
except DeployGuardError as error:83
print(str(error), file=sys.stderr)84
return 185
print('Deploy guard: projectmap ok.')86
# Path itself is not printed (secrets). Length only.87
print('projectftp length=%d' % len(path))88
return 089
90
91
if __name__ == '__main__':92
sys.exit(main())@@ -0,0 +1,120 @@
1
#!/usr/bin/env python3
2
"""Tests for writing data/config.php from the auth_client_secret CI secret.
3
4
Fake secrets below are test fixtures only. The real secret is never used here.
5
This file prints only pass/fail text, never a generated config or a secret.
6
"""
7
from __future__ import annotations
8
9
import os
10
import subprocess
11
import sys
12
import tempfile
13
from pathlib import Path
14
15
sys.path.insert(0, str(Path(__file__).resolve().parent))
16
from deploy import ( # noqa: E402
17
auth_config_php,
18
deploy_commands,
19
php_single_quoted,
20
)
21
22
FAKE = 'test-secret-value-NOT-FOR-PRODUCTION'
23
FAKE_QUOTED = "it's a \\secret with 'quotes'"
24
ENV = {
25
'timftphost': 'ftp://example.test',
26
'timftpuser': 'u',
27
'timftppassword': 'p',
28
}
29
30
31
def check(cond, msg):
32
if not cond:
33
raise SystemExit('FAIL: ' + msg)
34
35
36
def test_empty_secret():
37
check(auth_config_php({}) is None, 'unset → None')
38
check(auth_config_php({'auth_client_secret': ''}) is None, 'empty → None')
39
check(auth_config_php({'auth_client_secret': ' '}) is None, 'whitespace → None')
40
41
42
def test_php_quoting():
43
check(php_single_quoted('hello') == "'hello'", 'plain')
44
check(php_single_quoted("it's") == r"'it\'s'", 'quote')
45
check(php_single_quoted('a\\b') == r"'a\\b'", 'backslash')
46
47
48
def test_generated_php_evaluates():
49
php = auth_config_php({'auth_client_secret': FAKE_QUOTED, 'auth_client_id': ''})
50
check(php is not None, 'php generated')
51
check('projects.timfalken.com' in php, 'default client_id')
52
check('https://projects.timfalken.com/allianties' in php, 'base_url')
53
php2 = auth_config_php({
54
'auth_client_secret': FAKE,
55
'auth_client_id': 'other.example',
56
})
57
check('other.example' in php2, 'optional auth_client_id')
58
59
cfg = Path(tempfile.mkstemp(suffix='.php')[1])
60
wrp = Path(tempfile.mkstemp(suffix='.php')[1])
61
cfg.write_text(php)
62
# Wrapper prints only safe fields and a MATCH flag; never the secret.
63
wrp.write_text(
64
"<?php\n"
65
"$c = require $argv[1];\n"
66
"echo $c['client_id'], chr(10), $c['base_url'], chr(10), "
67
"strlen($c['client_secret']), chr(10), "
68
"($c['client_secret'] === $argv[2] ? 'MATCH' : 'MISMATCH'), chr(10);\n"
69
)
70
try:
71
result = subprocess.run(
72
['php', str(wrp), str(cfg), FAKE_QUOTED],
73
capture_output=True,
74
text=True,
75
check=False,
76
)
77
finally:
78
cfg.unlink(missing_ok=True)
79
wrp.unlink(missing_ok=True)
80
if result.returncode != 0:
81
# Redact any accidental secret material before printing.
82
blob = (result.stdout + '\n' + result.stderr).replace(FAKE_QUOTED, '[FAKE]').replace(FAKE, '[FAKE]')
83
raise SystemExit('FAIL: php exit %s: %s' % (result.returncode, blob[:300]))
84
lines = result.stdout.strip().splitlines()
85
check(len(lines) >= 4, 'php output lines')
86
check(lines[0] == 'projects.timfalken.com', 'client_id eval')
87
check(lines[1] == 'https://projects.timfalken.com/allianties', 'base_url eval')
88
check(lines[3] == 'MATCH', 'secret round-trip')
89
check(FAKE_QUOTED not in result.stdout, 'php test stdout leaked secret')
90
91
92
def test_lftp_script_has_no_secret():
93
cmds = '\n'.join(deploy_commands(ENV, '/var/www/allianties', Path('build')))
94
check('--delete' not in cmds, 'no --delete')
95
check('--exclude-glob "**/config.php"' in cmds, 'mirror excludes config')
96
check('--exclude-glob "data/**"' in cmds, 'mirror excludes data')
97
check(' -o data/config.php' not in cmds, 'no put without secret path')
98
check('data/.htaccess' in cmds, 'htaccess still put')
99
100
path = '/tmp/allianties-auth-XXXX/config.php'
101
cmds2 = '\n'.join(
102
deploy_commands(ENV, '/var/www/allianties', Path('build'), auth_config_path=path)
103
)
104
check(' -o data/config.php' in cmds2, 'put when path given')
105
check(path in cmds2, 'local path in put')
106
check(FAKE not in cmds2 and FAKE_QUOTED not in cmds2, 'secret not in lftp script')
107
check('--delete' not in cmds2, 'no --delete with config put')
108
109
110
def main():
111
test_empty_secret()
112
test_php_quoting()
113
test_generated_php_evaluates()
114
test_lftp_script_has_no_secret()
115
print('auth-config ok')
116
return 0
117
118
119
if __name__ == '__main__':
120
sys.exit(main())
@@ -0,0 +1,120 @@1
#!/usr/bin/env python32
"""Tests for writing data/config.php from the auth_client_secret CI secret.3
4
Fake secrets below are test fixtures only. The real secret is never used here.5
This file prints only pass/fail text, never a generated config or a secret.6
"""7
from __future__ import annotations8
9
import os10
import subprocess11
import sys12
import tempfile13
from pathlib import Path14
15
sys.path.insert(0, str(Path(__file__).resolve().parent))16
from deploy import ( # noqa: E40217
auth_config_php,18
deploy_commands,19
php_single_quoted,20
)21
22
FAKE = 'test-secret-value-NOT-FOR-PRODUCTION'23
FAKE_QUOTED = "it's a \\secret with 'quotes'"24
ENV = {25
'timftphost': 'ftp://example.test',26
'timftpuser': 'u',27
'timftppassword': 'p',28
}29
30
31
def check(cond, msg):32
if not cond:33
raise SystemExit('FAIL: ' + msg)34
35
36
def test_empty_secret():37
check(auth_config_php({}) is None, 'unset → None')38
check(auth_config_php({'auth_client_secret': ''}) is None, 'empty → None')39
check(auth_config_php({'auth_client_secret': ' '}) is None, 'whitespace → None')40
41
42
def test_php_quoting():43
check(php_single_quoted('hello') == "'hello'", 'plain')44
check(php_single_quoted("it's") == r"'it\'s'", 'quote')45
check(php_single_quoted('a\\b') == r"'a\\b'", 'backslash')46
47
48
def test_generated_php_evaluates():49
php = auth_config_php({'auth_client_secret': FAKE_QUOTED, 'auth_client_id': ''})50
check(php is not None, 'php generated')51
check('projects.timfalken.com' in php, 'default client_id')52
check('https://projects.timfalken.com/allianties' in php, 'base_url')53
php2 = auth_config_php({54
'auth_client_secret': FAKE,55
'auth_client_id': 'other.example',56
})57
check('other.example' in php2, 'optional auth_client_id')58
59
cfg = Path(tempfile.mkstemp(suffix='.php')[1])60
wrp = Path(tempfile.mkstemp(suffix='.php')[1])61
cfg.write_text(php)62
# Wrapper prints only safe fields and a MATCH flag; never the secret.63
wrp.write_text(64
"<?php\n"65
"$c = require $argv[1];\n"66
"echo $c['client_id'], chr(10), $c['base_url'], chr(10), "67
"strlen($c['client_secret']), chr(10), "68
"($c['client_secret'] === $argv[2] ? 'MATCH' : 'MISMATCH'), chr(10);\n"69
)70
try:71
result = subprocess.run(72
['php', str(wrp), str(cfg), FAKE_QUOTED],73
capture_output=True,74
text=True,75
check=False,76
)77
finally:78
cfg.unlink(missing_ok=True)79
wrp.unlink(missing_ok=True)80
if result.returncode != 0:81
# Redact any accidental secret material before printing.82
blob = (result.stdout + '\n' + result.stderr).replace(FAKE_QUOTED, '[FAKE]').replace(FAKE, '[FAKE]')83
raise SystemExit('FAIL: php exit %s: %s' % (result.returncode, blob[:300]))84
lines = result.stdout.strip().splitlines()85
check(len(lines) >= 4, 'php output lines')86
check(lines[0] == 'projects.timfalken.com', 'client_id eval')87
check(lines[1] == 'https://projects.timfalken.com/allianties', 'base_url eval')88
check(lines[3] == 'MATCH', 'secret round-trip')89
check(FAKE_QUOTED not in result.stdout, 'php test stdout leaked secret')90
91
92
def test_lftp_script_has_no_secret():93
cmds = '\n'.join(deploy_commands(ENV, '/var/www/allianties', Path('build')))94
check('--delete' not in cmds, 'no --delete')95
check('--exclude-glob "**/config.php"' in cmds, 'mirror excludes config')96
check('--exclude-glob "data/**"' in cmds, 'mirror excludes data')97
check(' -o data/config.php' not in cmds, 'no put without secret path')98
check('data/.htaccess' in cmds, 'htaccess still put')99
100
path = '/tmp/allianties-auth-XXXX/config.php'101
cmds2 = '\n'.join(102
deploy_commands(ENV, '/var/www/allianties', Path('build'), auth_config_path=path)103
)104
check(' -o data/config.php' in cmds2, 'put when path given')105
check(path in cmds2, 'local path in put')106
check(FAKE not in cmds2 and FAKE_QUOTED not in cmds2, 'secret not in lftp script')107
check('--delete' not in cmds2, 'no --delete with config put')108
109
110
def main():111
test_empty_secret()112
test_php_quoting()113
test_generated_php_evaluates()114
test_lftp_script_has_no_secret()115
print('auth-config ok')116
return 0117
118
119
if __name__ == '__main__':120
sys.exit(main())@@ -0,0 +1,231 @@
1
# Aannames — Allianties
2
3
Waar de specificatie ruimte liet, gelden deze keuzes. Ze zijn ook in de
4
regelmotor (`server/lib/Engine.php`) en de tests vastgelegd.
5
6
## Bord en plaatsing
7
8
- Het bord is vierkant. Grootte: `max(6, ceil(sqrt(n × 6)))`. Twee tot
9
zes spelers: 6×6; acht spelers: 7×7; twaalf: 9×9.
10
- Startposities liggen op een ring rond het midden, beginnend bovenaan en
11
dan met de klok mee. Bij een botsing schuift de speler naar het dichtstbij
12
zijnde vrije vakje. Dode spelers blokkeren geen vakjes meer, maar blijven
13
visueel op hun laatste plek (uitgegrijsd).
14
- Maximaal 16 spelers per spel, minimaal 2 om te starten. Er is geen
15
aparte “klaar”-stap: de host start wanneer er minstens twee spelers zijn.
16
- Kleuren van de omlijning worden in volgorde van aansluiting uit een vaste
17
palet van 16 contrasterende kleuren gekozen.
18
19
## Actiepunten en tijd
20
21
- Iedereen begint bij de start met 1 actiepunt, zodat je meteen kunt
22
handelen.
23
- Daarna krijgt elke levende speler 1 punt bij elke dagelijkse uitdeling
24
(Europe/Amsterdam). Het tijdstip is per lobby instelbaar, standaard
25
**00:00**, en volgt de wissel naar en van zomertijd. Als de server een
26
paar dagen offline was, worden gemiste uitdelingen bij de volgende
27
request ingehaald.
28
- De countdown bovenaan is `HH:MM:SS` tot de volgende uitdeling, op basis
29
van de servertijd (met correctie voor klokverschil in de browser) en tikt
30
live zolang het tabblad open is.
31
- Bereik heeft een plafond gelijk aan de maximale Chebyshev-afstand op het
32
bord (`grootte − 1`), zodat “het hele bord” het maximum is.
33
- Meerdere actiepunten in één keer geven telt als één actie (één tik op de
34
tijdlijn).
35
36
## Jury (standaard aan, in de lobby uit te zetten)
37
38
- Alleen uitgeschakelde deelnemers (inclusief wie zich heeft overgegeven)
39
mogen stemmen, en alleen op een levende speler.
40
- Stemmen zijn geheim: anderen zien jouw stem niet. Je kunt hem wijzigen
41
tot de uitdeling. Daarna worden de stemmen gewist voor de nieuwe dag.
42
- Bij een unieke winnaar krijgt die +1 AP bovenop het dagelijkse punt.
43
**Bij een gelijke stand krijgt iedere gelijkstaande levende speler de
44
bonus.** Als niemand heeft gestemd, is er geen bonus.
45
- De bonus wordt ná een eventuele krimp uitgedeeld, zodat wie die dag
46
door de krimp sterft geen punten meer krijgt.
47
48
## Krimpend speelveld (standaard uit)
49
50
- De host zet het interval (1–30 dagen, standaard 7). De eerste krimp is
51
op uitdeling nummer *N* na de start (dag *N*), daarna elke *N* dagen, op het AP-tijdstip van de lobby.
52
- Elke krimp maakt de buitenste begaanbare ring onbegaanbaar
53
(`arena_inset` + 1). Minimum speelbaar veld is 3×3, dus op een 6×6-bord
54
stopt de krimp bij 4×4 (`max_inset = floor((grootte − 3) / 2)`).
55
- Spelers op de nieuwe ring verliezen 1 leven. Overleven ze, dan gaan ze
56
naar het dichtstbijzijnde vrije begaanbare vakje (eerst Chebyshev, dan
57
Euclidean naar het midden, dan een vaste (y, x)-volgorde). Spelers worden
58
in volgorde van hun id verplaatst, zodat het deterministisch is.
59
- Is er géén vrij begaanbaar vakje meer, dan is de speler
60
**vermorzeld**: 0 levens, uitgeschakeld.
61
- Sterven de laatste twee (of meer) in dezelfde krimp, dan is het
62
**gelijkspel**.
63
- De UI toont wanneer de volgende krimp is en markeert de ring die dan
64
verdwijnt.
65
66
## Gedwongen staakt-het-vuren (standaard uit)
67
68
- De host tekent één of meer periodes op een 24-uursklok (0 bovenaan, met
69
de klok mee), of vult exacte tijden in. Periodes mogen over middernacht
70
lopen. Een periode met gelijke begin- en eindtijd wordt genegeerd.
71
Overlappende periodes worden voor de countdown samengevoegd.
72
- Tijden zijn wandkloktijden in **Europe/Amsterdam**. Bij de overgang naar
73
zomertijd is een periode korter in echte seconden (het overgeslagen uur
74
telt niet); bij de terugzetting is hij langer (het herhaalde uur telt
75
twee keer). Het einde van een periode is exclusief (06:00 precies is
76
niet meer staakt-het-vuren als de periode tot 06:00 loopt).
77
- Tijdens het staakt-het-vuren is schieten server-side geweigerd
78
(`ceasefire`). Bewegen, punten geven, bereik vergroten, overgeven,
79
stemmen, notities en chat blijven mogelijk. De knop Aanvallen is
80
uitgeschakeld met een toelichting.
81
- Onder de AP-timer staat “Tijd over in het staakt-het-vuren: HH:MM:SS”
82
of “Tijd tot het staakt-het-vuren: HH:MM:SS”.
83
- Staat de regel aan zonder periodes, dan is er feitelijk geen
84
staakt-het-vuren.
85
86
## Lobby, sessie, verwante zaken
87
88
- Uitnodigen gaat via een 6-teken-code (zonder 0/O/I/1/L) en een deelbare
89
link `?join=CODE`. Na inloggen kom je terug bij die link.
90
- Verlaat de host de lobby vóór de start, dan wordt de vroegst
91
aangesloten overgebleven speler de nieuwe host. Is de lobby leeg, dan
92
verdwijnt hij.
93
- Tijdens een lopend spel kun je niet meer instappen. Eén speler mag in
94
meerdere spellen tegelijk zitten.
95
- Overgeven maakt je dood (0 levens, vlag `surrendered`); je mag daarna
96
nog wel als jury stemmen en berichten sturen, als de jury aan staat.
97
- Privénotities staan server-side, per kijker, over een andere (of jezelf)
98
speler. Chat is 1:1, alleen zichtbaar voor de twee betrokkenen. Dode
99
spelers mogen nog chatten.
100
- Sessie duurt 30 dagen en wordt bij activiteit verlengd. Avatar komt uit
101
het profiel van auth.timfalken.com (`avatar_url` / `avatar` / `picture`)
102
of, als fallback, `https://auth.timfalken.com/avatar/{id}`. Bij een
103
ontbrekende afbeelding toont de client initialen.
104
- Taalcodes volgen Meteors: intern `zh` (HTML `zh-Hans`), vlaggen `gb`,
105
`jp`, `cn`, `kr`. De keuze staat in `localStorage` (`allianties-locale`)
106
en in het profiel.
107
- Extra regels (harten op het bord, levens kopen, AP plunderen bij een
108
kill, …) zijn nog niet gebouwd; de motor is modulair zodat ze later als
109
schakelaar kunnen.
110
111
112
113
## Actiepunten-tijdstip en plunderen
114
115
- Elke lobby heeft een **dagelijks AP-tijdstip** (Europe/Amsterdam),
116
standaard 00:00. De host stelt het in met een tijdkiezer. Op dat
117
moment gebeuren de AP-uitdeling, de jurybonus en (indien aan) het
118
krimpen van het veld. Een “dag” in het spel is één zo’n uitdeling.
119
Bij een DST-lentesprong bestaat een gekozen tijd in de overgeslagen
120
periode (bijv. 02:30) niet; PHP landt op het eerste geldige moment
121
daarna (typisch 03:30 CEST). Bij de herfst blijft 02:30 geldig
122
(PHP gebruikt de eerste voorkomst).
123
- **Actiepunten plunderen bij een kill** staat standaard uit. Als de
124
host het aanzet, krijgt de schutter bij een *uitschakelend* schot de
125
resterende AP van het doelwit (ná het uitgeven van 1 AP voor het
126
schot). Overgave en krimp/verpletteren geven geen AP. Het geplunderde
127
aantal staat op het schot-event (`loot`) en is zichtbaar volgens de
128
AP-zichtbaarheidsregel (de schutter ziet het altijd).
129
- Er zijn **geen harten** op het bord en je kunt **geen levens kopen**.
130
Die regels bestaan niet als optie.
131
132
## Tijdlijnbediening
133
134
Op de tijdlijnbalk: stap terug, afspelen/pauzeren, stap vooruit, en
135
“Live” (naar het heden). Toetsen (alleen in een lopend spel, niet in
136
een invoerveld): ← stap terug, → stap vooruit, spatiebalk afspelen of
137
pauzeren, End springt naar het heden. Klikken/tikken ergens op de balk
138
springt naar het dichtstbijzijnde event; slepen scrubt.
139
140
## Zichtbaarheid (lobby-opties)
141
142
Standaard staat elke optie op de meest open waarde, **Openbaar**. De host
143
kiest dit in de lobby; na de start liggen de regels vast. De server filtert
144
iedere API-response (volle staat, sync, tijdlijn, replay) per kijker. Eigen
145
gegevens (levens, actiepunten, bereik) zijn altijd zichtbaar voor jezelf.
146
Verplaatsingen zijn altijd openbaar. Levend/dood en overgave zijn altijd
147
openbaar (nodig voor de jury en de winstvoorwaarde); verborgen is alleen
148
het resterende *aantal* levens.
149
150
- **Schoten:** *Openbaar* — iedereen ziet elk schot (schutter, doelwit,
151
schade). *Alleen uitschakelende schoten zijn openbaar* — een schot dat
152
niet elimineert is alleen zichtbaar voor schutter en doelwit; een
153
uitschakelend schot is voor iedereen zichtbaar (inclusief wie schoot).
154
*Alleen bekend bij het doelwit* — alleen schutter en doelwit zien het
155
schot, ook als het elimineert; anderen zien wel de dood, maar zonder
156
schutter (`by` wordt weggelaten). *Alleen een uitschakelend schot is
157
bekend bij het doelwit* — een niet-uitschakelend schot is alleen voor
158
de schutter zichtbaar (het doelwit ziet het eigen levensverlies, niet
159
van wie); een uitschakelend schot is bekend bij schutter en doelwit;
160
anderen zien de dood zonder schutter.
161
- **Giften:** *Openbaar* — iedereen ziet gever, ontvanger en aantal.
162
*Alleen bekend bij de ontvanger* — gever en ontvanger zien de gift
163
volledig; anderen zien niets. *Anoniem* — de ontvanger ziet dat hij
164
punten krijgt en hoeveel, maar niet van wie (`player` wordt weggelaten,
165
`anonymous: true`). Anderen zien de gift niet. De gever ziet de eigen
166
gift altijd.
167
- **Actiepuntentotalen:** *Openbaar* of *Verborgen*. Bij verborgen is
168
alleen je eigen totaal in de staat aanwezig; in het dagelijkse event
169
staat alleen je eigen toekenning. Jury-winnaars blijven openbaar
170
(de bekendmaking); stemtellingen worden niet meegestuurd.
171
- **Bereik:** *Openbaar*, *Bekend bij spelers binnen bereik*, of
172
*Verborgen*. “Binnen bereik” betekent: Chebyshev-afstand tot die
173
speler ≤ **diens** huidige bereik (je staat in hun schootsveld).
174
Upgrade-events volgen dezelfde regel, op basis van de *huidige*
175
posities (niet de historische).
176
- **Levens:** *Openbaar* of *Verborgen*. Bij een zichtbaar schot gaat
177
`lives_left` alleen mee als levens openbaar zijn of jij het doelwit
178
bent. De schade van het schot (`damage`, nu altijd 1) is wel zichtbaar
179
als je het schot mag zien — dat lekt het resterende aantal levens niet.
180
- Verborgen events worden **volledig weggelaten** (geen generiek streepje
181
op de tijdlijn): een streepje zou lekken *dat* er iets gebeurde.
182
Ticks en replay tonen alleen events die deze kijker mag zien.
183
- De opgeslagen wedstrijd blijft ongefilterd; `present()` stuurt een
184
kopie. Combinaties van opties kunnen aftellen mogelijk maken (bijv.
185
openbare AP-totalen plus anonieme giften); dat is een keuze van de
186
host. Bij openbare levens en verborgen niet-uitschakelende schoten
187
kan een levensverandering in de staat zichtbaar zijn zonder bijbehorend
188
schot-event; de replay verzint geen events.
189
190
## Weergave van events (geen tekstlog)
191
192
Er is geen tekstlog van zetten. Events zijn alleen te zien in de
193
**video-weergave** van de tijdlijn (afspelen 1 actie per 0,5 s, of
194
scrubben):
195
196
- Een gift: groene pijl van gever naar ontvanger, met het aantal AP.
197
Bij een anonieme gift (voor de ontvanger) verschijnt alleen “+N” op de
198
ontvanger, **zonder** bronpijl — een pijl “van nergens” zou nog een
199
richting kunnen suggereren en zo de gever verraden.
200
- Een schot: rode pijl van schutter naar doelwit, met de schade (levens
201
die dit schot kost). Alleen als dit event voor de kijker zichtbaar is.
202
- Een zet: de pion schuift van het oude naar het nieuwe vak.
203
- Een bereik-upgrade: een korte gouden pulsering om de pion.
204
- Levens, AP en bereik staan in het Info-venster van een speler, en
205
alleen als ze voor de kijker zichtbaar zijn (anders “Verborgen”).
206
Er staan geen permanente getallen op het bord voor verborgen stats.
207
208
Klikken of tikken **ergens op de tijdlijnbalk** springt naar het
209
dichtstbijzijnde event. Slepen scrubt door de events. Dit werkt met
210
muis en touch (`pointer` + `touch`, `touch-action: none`).
211
212
De uitnodigingslink (`?join=CODE`) herstelt na een verversing de lobby
213
of, als het spel al loopt en je lid bent, het lopende spel.
214
215
## Techniek
216
217
- Geen WebGL/frameworkv3: het bord, de avatars, de modals en de tijdlijn
218
zijn DOM+CSS, beter voor touch, tekst en toegankelijkheid. De rest van
219
de stapel (PHP-API, SQLite, CI, OAuth, i18n) volgt Meteors.
220
- Elke mutatie loopt in `BEGIN IMMEDIATE`. Een geweigerde zet rolt terug.
221
- De client polt elke 3 seconden een licht `sync`-eindpunt (versie,
222
servertijd, countdowns). Alleen bij een gewijzigde versie komt de volle
223
staat, inclusief chat. Bij een verborgen tabblad stopt het pollen; bij
224
terugkeer volgt een volle verversing.
225
- Lokale testers: `auth.php?test=1` t/m `?test=8`, alleen op localhost.
226
Op de live site staat dat uit.
227
- Het OAuth-callbackpad is `https://projects.timfalken.com/allianties/callback.php`.
228
Dat moet op auth.timfalken.com bij de bestaande client
229
`projects.timfalken.com` worden toegevoegd. Het clientgeheim wordt níet
230
opnieuw gegenereerd (dat zou de andere sites breken) en komt als
231
projectgeheim `auth_client_secret` in de CI.
@@ -0,0 +1,231 @@1
# Aannames — Allianties2
3
Waar de specificatie ruimte liet, gelden deze keuzes. Ze zijn ook in de4
regelmotor (`server/lib/Engine.php`) en de tests vastgelegd.5
6
## Bord en plaatsing7
8
- Het bord is vierkant. Grootte: `max(6, ceil(sqrt(n × 6)))`. Twee tot9
zes spelers: 6×6; acht spelers: 7×7; twaalf: 9×9.10
- Startposities liggen op een ring rond het midden, beginnend bovenaan en11
dan met de klok mee. Bij een botsing schuift de speler naar het dichtstbij12
zijnde vrije vakje. Dode spelers blokkeren geen vakjes meer, maar blijven13
visueel op hun laatste plek (uitgegrijsd).14
- Maximaal 16 spelers per spel, minimaal 2 om te starten. Er is geen15
aparte “klaar”-stap: de host start wanneer er minstens twee spelers zijn.16
- Kleuren van de omlijning worden in volgorde van aansluiting uit een vaste17
palet van 16 contrasterende kleuren gekozen.18
19
## Actiepunten en tijd20
21
- Iedereen begint bij de start met 1 actiepunt, zodat je meteen kunt22
handelen.23
- Daarna krijgt elke levende speler 1 punt bij elke dagelijkse uitdeling24
(Europe/Amsterdam). Het tijdstip is per lobby instelbaar, standaard25
**00:00**, en volgt de wissel naar en van zomertijd. Als de server een26
paar dagen offline was, worden gemiste uitdelingen bij de volgende27
request ingehaald.28
- De countdown bovenaan is `HH:MM:SS` tot de volgende uitdeling, op basis29
van de servertijd (met correctie voor klokverschil in de browser) en tikt30
live zolang het tabblad open is.31
- Bereik heeft een plafond gelijk aan de maximale Chebyshev-afstand op het32
bord (`grootte − 1`), zodat “het hele bord” het maximum is.33
- Meerdere actiepunten in één keer geven telt als één actie (één tik op de34
tijdlijn).35
36
## Jury (standaard aan, in de lobby uit te zetten)37
38
- Alleen uitgeschakelde deelnemers (inclusief wie zich heeft overgegeven)39
mogen stemmen, en alleen op een levende speler.40
- Stemmen zijn geheim: anderen zien jouw stem niet. Je kunt hem wijzigen41
tot de uitdeling. Daarna worden de stemmen gewist voor de nieuwe dag.42
- Bij een unieke winnaar krijgt die +1 AP bovenop het dagelijkse punt.43
**Bij een gelijke stand krijgt iedere gelijkstaande levende speler de44
bonus.** Als niemand heeft gestemd, is er geen bonus.45
- De bonus wordt ná een eventuele krimp uitgedeeld, zodat wie die dag46
door de krimp sterft geen punten meer krijgt.47
48
## Krimpend speelveld (standaard uit)49
50
- De host zet het interval (1–30 dagen, standaard 7). De eerste krimp is51
op uitdeling nummer *N* na de start (dag *N*), daarna elke *N* dagen, op het AP-tijdstip van de lobby.52
- Elke krimp maakt de buitenste begaanbare ring onbegaanbaar53
(`arena_inset` + 1). Minimum speelbaar veld is 3×3, dus op een 6×6-bord54
stopt de krimp bij 4×4 (`max_inset = floor((grootte − 3) / 2)`).55
- Spelers op de nieuwe ring verliezen 1 leven. Overleven ze, dan gaan ze56
naar het dichtstbijzijnde vrije begaanbare vakje (eerst Chebyshev, dan57
Euclidean naar het midden, dan een vaste (y, x)-volgorde). Spelers worden58
in volgorde van hun id verplaatst, zodat het deterministisch is.59
- Is er géén vrij begaanbaar vakje meer, dan is de speler60
**vermorzeld**: 0 levens, uitgeschakeld.61
- Sterven de laatste twee (of meer) in dezelfde krimp, dan is het62
**gelijkspel**.63
- De UI toont wanneer de volgende krimp is en markeert de ring die dan64
verdwijnt.65
66
## Gedwongen staakt-het-vuren (standaard uit)67
68
- De host tekent één of meer periodes op een 24-uursklok (0 bovenaan, met69
de klok mee), of vult exacte tijden in. Periodes mogen over middernacht70
lopen. Een periode met gelijke begin- en eindtijd wordt genegeerd.71
Overlappende periodes worden voor de countdown samengevoegd.72
- Tijden zijn wandkloktijden in **Europe/Amsterdam**. Bij de overgang naar73
zomertijd is een periode korter in echte seconden (het overgeslagen uur74
telt niet); bij de terugzetting is hij langer (het herhaalde uur telt75
twee keer). Het einde van een periode is exclusief (06:00 precies is76
niet meer staakt-het-vuren als de periode tot 06:00 loopt).77
- Tijdens het staakt-het-vuren is schieten server-side geweigerd78
(`ceasefire`). Bewegen, punten geven, bereik vergroten, overgeven,79
stemmen, notities en chat blijven mogelijk. De knop Aanvallen is80
uitgeschakeld met een toelichting.81
- Onder de AP-timer staat “Tijd over in het staakt-het-vuren: HH:MM:SS”82
of “Tijd tot het staakt-het-vuren: HH:MM:SS”.83
- Staat de regel aan zonder periodes, dan is er feitelijk geen84
staakt-het-vuren.85
86
## Lobby, sessie, verwante zaken87
88
- Uitnodigen gaat via een 6-teken-code (zonder 0/O/I/1/L) en een deelbare89
link `?join=CODE`. Na inloggen kom je terug bij die link.90
- Verlaat de host de lobby vóór de start, dan wordt de vroegst91
aangesloten overgebleven speler de nieuwe host. Is de lobby leeg, dan92
verdwijnt hij.93
- Tijdens een lopend spel kun je niet meer instappen. Eén speler mag in94
meerdere spellen tegelijk zitten.95
- Overgeven maakt je dood (0 levens, vlag `surrendered`); je mag daarna96
nog wel als jury stemmen en berichten sturen, als de jury aan staat.97
- Privénotities staan server-side, per kijker, over een andere (of jezelf)98
speler. Chat is 1:1, alleen zichtbaar voor de twee betrokkenen. Dode99
spelers mogen nog chatten.100
- Sessie duurt 30 dagen en wordt bij activiteit verlengd. Avatar komt uit101
het profiel van auth.timfalken.com (`avatar_url` / `avatar` / `picture`)102
of, als fallback, `https://auth.timfalken.com/avatar/{id}`. Bij een103
ontbrekende afbeelding toont de client initialen.104
- Taalcodes volgen Meteors: intern `zh` (HTML `zh-Hans`), vlaggen `gb`,105
`jp`, `cn`, `kr`. De keuze staat in `localStorage` (`allianties-locale`)106
en in het profiel.107
- Extra regels (harten op het bord, levens kopen, AP plunderen bij een108
kill, …) zijn nog niet gebouwd; de motor is modulair zodat ze later als109
schakelaar kunnen.110
111
112
113
## Actiepunten-tijdstip en plunderen114
115
- Elke lobby heeft een **dagelijks AP-tijdstip** (Europe/Amsterdam),116
standaard 00:00. De host stelt het in met een tijdkiezer. Op dat117
moment gebeuren de AP-uitdeling, de jurybonus en (indien aan) het118
krimpen van het veld. Een “dag” in het spel is één zo’n uitdeling.119
Bij een DST-lentesprong bestaat een gekozen tijd in de overgeslagen120
periode (bijv. 02:30) niet; PHP landt op het eerste geldige moment121
daarna (typisch 03:30 CEST). Bij de herfst blijft 02:30 geldig122
(PHP gebruikt de eerste voorkomst).123
- **Actiepunten plunderen bij een kill** staat standaard uit. Als de124
host het aanzet, krijgt de schutter bij een *uitschakelend* schot de125
resterende AP van het doelwit (ná het uitgeven van 1 AP voor het126
schot). Overgave en krimp/verpletteren geven geen AP. Het geplunderde127
aantal staat op het schot-event (`loot`) en is zichtbaar volgens de128
AP-zichtbaarheidsregel (de schutter ziet het altijd).129
- Er zijn **geen harten** op het bord en je kunt **geen levens kopen**.130
Die regels bestaan niet als optie.131
132
## Tijdlijnbediening133
134
Op de tijdlijnbalk: stap terug, afspelen/pauzeren, stap vooruit, en135
“Live” (naar het heden). Toetsen (alleen in een lopend spel, niet in136
een invoerveld): ← stap terug, → stap vooruit, spatiebalk afspelen of137
pauzeren, End springt naar het heden. Klikken/tikken ergens op de balk138
springt naar het dichtstbijzijnde event; slepen scrubt.139
140
## Zichtbaarheid (lobby-opties)141
142
Standaard staat elke optie op de meest open waarde, **Openbaar**. De host143
kiest dit in de lobby; na de start liggen de regels vast. De server filtert144
iedere API-response (volle staat, sync, tijdlijn, replay) per kijker. Eigen145
gegevens (levens, actiepunten, bereik) zijn altijd zichtbaar voor jezelf.146
Verplaatsingen zijn altijd openbaar. Levend/dood en overgave zijn altijd147
openbaar (nodig voor de jury en de winstvoorwaarde); verborgen is alleen148
het resterende *aantal* levens.149
150
- **Schoten:** *Openbaar* — iedereen ziet elk schot (schutter, doelwit,151
schade). *Alleen uitschakelende schoten zijn openbaar* — een schot dat152
niet elimineert is alleen zichtbaar voor schutter en doelwit; een153
uitschakelend schot is voor iedereen zichtbaar (inclusief wie schoot).154
*Alleen bekend bij het doelwit* — alleen schutter en doelwit zien het155
schot, ook als het elimineert; anderen zien wel de dood, maar zonder156
schutter (`by` wordt weggelaten). *Alleen een uitschakelend schot is157
bekend bij het doelwit* — een niet-uitschakelend schot is alleen voor158
de schutter zichtbaar (het doelwit ziet het eigen levensverlies, niet159
van wie); een uitschakelend schot is bekend bij schutter en doelwit;160
anderen zien de dood zonder schutter.161
- **Giften:** *Openbaar* — iedereen ziet gever, ontvanger en aantal.162
*Alleen bekend bij de ontvanger* — gever en ontvanger zien de gift163
volledig; anderen zien niets. *Anoniem* — de ontvanger ziet dat hij164
punten krijgt en hoeveel, maar niet van wie (`player` wordt weggelaten,165
`anonymous: true`). Anderen zien de gift niet. De gever ziet de eigen166
gift altijd.167
- **Actiepuntentotalen:** *Openbaar* of *Verborgen*. Bij verborgen is168
alleen je eigen totaal in de staat aanwezig; in het dagelijkse event169
staat alleen je eigen toekenning. Jury-winnaars blijven openbaar170
(de bekendmaking); stemtellingen worden niet meegestuurd.171
- **Bereik:** *Openbaar*, *Bekend bij spelers binnen bereik*, of172
*Verborgen*. “Binnen bereik” betekent: Chebyshev-afstand tot die173
speler ≤ **diens** huidige bereik (je staat in hun schootsveld).174
Upgrade-events volgen dezelfde regel, op basis van de *huidige*175
posities (niet de historische).176
- **Levens:** *Openbaar* of *Verborgen*. Bij een zichtbaar schot gaat177
`lives_left` alleen mee als levens openbaar zijn of jij het doelwit178
bent. De schade van het schot (`damage`, nu altijd 1) is wel zichtbaar179
als je het schot mag zien — dat lekt het resterende aantal levens niet.180
- Verborgen events worden **volledig weggelaten** (geen generiek streepje181
op de tijdlijn): een streepje zou lekken *dat* er iets gebeurde.182
Ticks en replay tonen alleen events die deze kijker mag zien.183
- De opgeslagen wedstrijd blijft ongefilterd; `present()` stuurt een184
kopie. Combinaties van opties kunnen aftellen mogelijk maken (bijv.185
openbare AP-totalen plus anonieme giften); dat is een keuze van de186
host. Bij openbare levens en verborgen niet-uitschakelende schoten187
kan een levensverandering in de staat zichtbaar zijn zonder bijbehorend188
schot-event; de replay verzint geen events.189
190
## Weergave van events (geen tekstlog)191
192
Er is geen tekstlog van zetten. Events zijn alleen te zien in de193
**video-weergave** van de tijdlijn (afspelen 1 actie per 0,5 s, of194
scrubben):195
196
- Een gift: groene pijl van gever naar ontvanger, met het aantal AP.197
Bij een anonieme gift (voor de ontvanger) verschijnt alleen “+N” op de198
ontvanger, **zonder** bronpijl — een pijl “van nergens” zou nog een199
richting kunnen suggereren en zo de gever verraden.200
- Een schot: rode pijl van schutter naar doelwit, met de schade (levens201
die dit schot kost). Alleen als dit event voor de kijker zichtbaar is.202
- Een zet: de pion schuift van het oude naar het nieuwe vak.203
- Een bereik-upgrade: een korte gouden pulsering om de pion.204
- Levens, AP en bereik staan in het Info-venster van een speler, en205
alleen als ze voor de kijker zichtbaar zijn (anders “Verborgen”).206
Er staan geen permanente getallen op het bord voor verborgen stats.207
208
Klikken of tikken **ergens op de tijdlijnbalk** springt naar het209
dichtstbijzijnde event. Slepen scrubt door de events. Dit werkt met210
muis en touch (`pointer` + `touch`, `touch-action: none`).211
212
De uitnodigingslink (`?join=CODE`) herstelt na een verversing de lobby213
of, als het spel al loopt en je lid bent, het lopende spel.214
215
## Techniek216
217
- Geen WebGL/frameworkv3: het bord, de avatars, de modals en de tijdlijn218
zijn DOM+CSS, beter voor touch, tekst en toegankelijkheid. De rest van219
de stapel (PHP-API, SQLite, CI, OAuth, i18n) volgt Meteors.220
- Elke mutatie loopt in `BEGIN IMMEDIATE`. Een geweigerde zet rolt terug.221
- De client polt elke 3 seconden een licht `sync`-eindpunt (versie,222
servertijd, countdowns). Alleen bij een gewijzigde versie komt de volle223
staat, inclusief chat. Bij een verborgen tabblad stopt het pollen; bij224
terugkeer volgt een volle verversing.225
- Lokale testers: `auth.php?test=1` t/m `?test=8`, alleen op localhost.226
Op de live site staat dat uit.227
- Het OAuth-callbackpad is `https://projects.timfalken.com/allianties/callback.php`.228
Dat moet op auth.timfalken.com bij de bestaande client229
`projects.timfalken.com` worden toegevoegd. Het clientgeheim wordt níet230
opnieuw gegenereerd (dat zou de andere sites breken) en komt als231
projectgeheim `auth_client_secret` in de CI.@@ -0,0 +1,10 @@
1
{
2
"name": "allianties",
3
"private": true,
4
"version": "0.1.0",
5
"description": "Allianties — Tank Turn Tactics on projects.timfalken.com",
6
"scripts": {
7
"build": "bash src/build.sh",
8
"test": "node --test test/*.test.js"
9
}
10
}
@@ -0,0 +1,10 @@1
{2
"name": "allianties",3
"private": true,4
"version": "0.1.0",5
"description": "Allianties — Tank Turn Tactics on projects.timfalken.com",6
"scripts": {7
"build": "bash src/build.sh",8
"test": "node --test test/*.test.js"9
}10
}@@ -0,0 +1,378 @@
1
#!/usr/bin/env python3
2
"""Generate server/lib/i18n.json for Allianties (10 locales, identical keys)."""
3
import json
4
from pathlib import Path
5
6
# The game name is never translated.
7
NAME = "Allianties"
8
9
# English is the source of truth. Every other locale must have the same keys.
10
EN = {
11
"app.name": NAME,
12
"menu.tagline": "A game of patience, alliances and well-timed shots.",
13
"menu.login": "Log in",
14
"menu.logout": "Log out",
15
"menu.loggedInAs": "Logged in as",
16
"menu.localTest": "local test:",
17
"menu.create": "New lobby",
18
"menu.join": "Join",
19
"menu.codePlaceholder": "Code",
20
"menu.myGames": "Your games",
21
"menu.noGames": "You have no games yet. Start a lobby and invite others.",
22
"menu.authUnconfiguredHtml": "Sign-in is not set up on this server yet. The callback <code>/allianties/callback.php</code> must be registered at auth.timfalken.com, and the client secret must be configured.",
23
"menu.guestHint": "Log in to create a lobby, invite players and start a lasting game.",
24
"menu.open": "Open",
25
"menu.continue": "Continue",
26
"menu.statusLobby": "Lobby",
27
"menu.statusRunning": "In play",
28
"menu.statusFinished": "Finished",
29
"menu.youWon": "You won",
30
"menu.draw": "Draw",
31
"menu.winnerIs": "Winner: {name}",
32
"menu.needLogin": "Log in first to play.",
33
"menu.players": "Players",
34
35
"lobby.title": "Lobby",
36
"lobby.invite": "Invite",
37
"lobby.copy": "Copy link",
38
"lobby.copied": "Copied",
39
"lobby.shareHint": "Share this code or link. Players log in and join.",
40
"lobby.players": "Players",
41
"lobby.start": "Start game",
42
"lobby.leave": "Leave lobby",
43
"lobby.host": "Host",
44
"lobby.you": "you",
45
"lobby.minPlayers": "You need at least two players to start.",
46
"lobby.needTwo": "Waiting for at least one more player…",
47
"lobby.rules": "Rules",
48
"lobby.jury": "Jury",
49
"lobby.juryHint": "Dead players vote each day for a living player. The player with the most votes receives one extra action point at the next daily distribution. Ties: every tied player receives the bonus. Votes are secret and can be changed until then.",
50
"lobby.shrink": "Shrinking arena",
51
"lobby.shrinkHint": "After every set number of days, the outer ring becomes impassable at the daily distribution. Players standing on it lose one life and are pushed inward.",
52
"lobby.shrinkDays": "Days between shrinks",
53
"lobby.shrinkDaysHint": "First shrink after this many midnights, then again each time that many days pass, until the arena reaches its minimum size.",
54
"lobby.ceasefire": "Forced cease-fire hours",
55
"lobby.ceasefireHint": "During these hours (Europe/Amsterdam) no one may shoot. Moving, giving action points and upgrading range remain allowed. Periods may wrap around midnight.",
56
"lobby.ceasefireAdd": "Add period",
57
"lobby.ceasefireRemove": "Remove",
58
"lobby.ceasefireStart": "From",
59
"lobby.ceasefireEnd": "Until",
60
"lobby.ceasefireEmpty": "No periods yet. Add one, or drag a slice on the clock.",
61
"lobby.ceasefireClock": "24-hour clock. Drag the handles or paint a slice; red is cease-fire, gold is open fire. Times are Europe/Amsterdam.",
62
"lobby.waiting": "Waiting for the host to start the game.",
63
"lobby.back": "Back",
64
"lobby.code": "Code",
65
"lobby.playerCount.one": "{n} player",
66
"lobby.playerCount.other": "{n} players",
67
"lobby.playerCount.few": "{n} players",
68
"lobby.playerCount.many": "{n} players",
69
70
"game.day": "Day {n}",
71
"game.nextAp": "Next action points",
72
"game.lives": "Lives",
73
"game.ap": "Action points",
74
"game.range": "Range",
75
"game.you": "You",
76
"game.dead": "Out",
77
"game.surrendered": "Surrendered",
78
"game.winner": "{name} wins!",
79
"game.youWin": "You win!",
80
"game.draw": "The game ends in a draw.",
81
"game.shrinkIn": "Arena shrinks in {n} days",
82
"game.shrinkInDays.one": "Arena shrinks in {n} day",
83
"game.shrinkInDays.other": "Arena shrinks in {n} days",
84
"game.shrinkInDays.few": "Arena shrinks in {n} days",
85
"game.shrinkInDays.many": "Arena shrinks in {n} days",
86
"game.shrinkTomorrow": "Arena shrinks tomorrow",
87
"game.shrinkToday": "Arena shrinks at the next distribution",
88
"game.upgrade": "Upgrade range",
89
"game.settings": "Settings",
90
"game.surrender": "Surrender",
91
"game.surrenderConfirm": "Surrender? You will be out of this game. This cannot be undone.",
92
"game.surrenderConfirmBtn": "Yes, surrender",
93
"game.surrenderCancel": "Cancel",
94
"game.back": "Back to menu",
95
"game.spectating": "You are out. You can still watch, send messages and, if the jury is on, vote.",
96
"game.ceasefireLeft": "Time left in cease-fire",
97
"game.ceasefireUntil": "Time until cease-fire",
98
"game.ceasefireActive": "Cease-fire",
99
"game.attackDisabled": "Attack",
100
"game.attackDisabledReason": "Attack is not allowed during cease-fire hours.",
101
"game.selectSelf": "Your tank is selected. Tap a highlighted tile to move, or upgrade your range.",
102
"game.impassable": "Impassable",
103
"game.willShrink": "This ring will shrink next",
104
105
"opt.info": "Info",
106
"opt.attack": "Attack",
107
"opt.give": "Give action points",
108
"opt.message": "Send message",
109
"opt.close": "Close",
110
111
"info.title": "Info",
112
"info.lives": "Lives",
113
"info.ap": "Action points",
114
"info.range": "Range",
115
"info.notes": "Your private notes",
116
"info.notesHint": "Only you can see these notes. They are stored with your account.",
117
"info.saveNotes": "Save notes",
118
"info.saved": "Saved",
119
120
"give.title": "Give action points",
121
"give.howMany": "How many?",
122
"give.send": "Give",
123
"give.youHave": "You have {n}.",
124
125
"chat.title": "Message {name}",
126
"chat.placeholder": "Write a private message…",
127
"chat.send": "Send",
128
"chat.empty": "No messages yet.",
129
130
"jury.title": "Jury",
131
"jury.hint": "Vote for one living player. The player with the most votes gets an extra action point at the next distribution. You can change your vote until then. Other players cannot see your vote.",
132
"jury.vote": "Vote",
133
"jury.votedFor": "You voted for {name}",
134
"jury.change": "Change vote",
135
136
"timeline.play": "Play",
137
"timeline.pause": "Pause",
138
"timeline.live": "Live",
139
"timeline.event.start": "The game begins",
140
"timeline.event.move": "{name} moves",
141
"timeline.event.shoot": "{name} shoots {target}",
142
"timeline.event.give": "{name} gives {n} action point(s) to {target}",
143
"timeline.event.upgrade": "{name} upgrades range to {n}",
144
"timeline.event.surrender": "{name} surrenders",
145
"timeline.event.daily": "Day {n}: action points are distributed",
146
"timeline.event.jury": "The jury awards a bonus to {name}",
147
"timeline.event.juryTie": "The jury awards a bonus to {names}",
148
"timeline.event.shrink": "The arena shrinks",
149
"timeline.event.win": "{name} wins",
150
"timeline.event.death": "{name} is out",
151
"timeline.event.deathShot": "{name} is shot by {by}",
152
"timeline.event.deathShrink": "{name} is caught by the shrinking arena",
153
"timeline.event.deathCrushed": "{name} is crushed: no free tile left",
154
"timeline.event.draw": "The game ends in a draw",
155
156
"auth.unavailable": "Sign-in is temporarily unavailable.",
157
"auth.backToGame": "Back to Allianties",
158
"auth.failed": "Sign-in failed.",
159
"auth.retry": "Try again",
160
"auth.back": "Back",
161
162
"lang.choose": "Choose language",
163
"lang.current": "Language: {name}",
164
165
"error.login": "Log in to continue.",
166
"error.csrf": "Your session expired. Refresh the page and try again.",
167
"error.not_host": "Only the host can do that.",
168
"error.min_players": "You need at least two players to start.",
169
"error.not_in_game": "You are not in this game.",
170
"error.dead": "You are out of this game.",
171
"error.no_ap": "You have no action points left.",
172
"error.occupied": "That tile is occupied.",
173
"error.impassable": "That tile is impassable.",
174
"error.out_of_range": "That player is out of range.",
175
"error.invalid_move": "That move is not allowed.",
176
"error.game_started": "This game has already started.",
177
"error.game_finished": "This game is over.",
178
"error.lobby_full": "This lobby is full.",
179
"error.unknown_code": "No lobby found with that code.",
180
"error.cannot_vote": "You cannot vote now.",
181
"error.bad_vote": "You can only vote for a living player.",
182
"error.bad_give": "You cannot give that many action points.",
183
"error.unknown_action": "Unknown action.",
184
"error.ceasefire": "You cannot attack during cease-fire hours.",
185
"error.generic": "Something went wrong. Please try again.",
186
"error.serverStatus": "The server returned {status}.",
187
}
188
189
# Translations. Every locale must include every EN key.
190
# "Allianties" stays Allianties everywhere.
191
192
NL = {
193
"app.name": NAME,
194
"menu.tagline": "Een spel van geduld, allianties en goed getimede schoten.",
195
"menu.login": "Inloggen",
196
"menu.logout": "Uitloggen",
197
"menu.loggedInAs": "Ingelogd als",
198
"menu.localTest": "lokale test:",
199
"menu.create": "Nieuwe lobby",
200
"menu.join": "Deelnemen",
201
"menu.codePlaceholder": "Code",
202
"menu.myGames": "Jouw spellen",
203
"menu.noGames": "Je hebt nog geen spellen. Start een lobby en nodig anderen uit.",
204
"menu.authUnconfiguredHtml": "Inloggen is op deze server nog niet ingesteld. De callback <code>/allianties/callback.php</code> moet bij auth.timfalken.com worden geregistreerd, en het clientgeheim moet worden gezet.",
205
"menu.guestHint": "Log in om een lobby te maken, spelers uit te nodigen en een blijvend spel te starten.",
206
"menu.open": "Openen",
207
"menu.continue": "Verder",
208
"menu.statusLobby": "Lobby",
209
"menu.statusRunning": "Bezig",
210
"menu.statusFinished": "Afgelopen",
211
"menu.youWon": "Jij won",
212
"menu.draw": "Gelijkspel",
213
"menu.winnerIs": "Winnaar: {name}",
214
"menu.needLogin": "Log eerst in om te spelen.",
215
"menu.players": "Spelers",
216
"lobby.title": "Lobby",
217
"lobby.invite": "Uitnodigen",
218
"lobby.copy": "Kopieer link",
219
"lobby.copied": "Gekopieerd",
220
"lobby.shareHint": "Deel deze code of link. Spelers loggen in en doen mee.",
221
"lobby.players": "Spelers",
222
"lobby.start": "Start spel",
223
"lobby.leave": "Lobby verlaten",
224
"lobby.host": "Host",
225
"lobby.you": "jij",
226
"lobby.minPlayers": "Je hebt minstens twee spelers nodig om te starten.",
227
"lobby.needTwo": "Wachten op minstens één speler extra…",
228
"lobby.rules": "Regels",
229
"lobby.jury": "Jury",
230
"lobby.juryHint": "Dode spelers stemmen elke dag op een levende speler. Wie de meeste stemmen krijgt, ontvangt één extra actiepunt bij de volgende dagelijkse uitdeling. Bij een gelijke stand krijgt iedere gelijkstaande speler de bonus. Stemmen zijn geheim en tot dan toe te wijzigen.",
231
"lobby.shrink": "Krimpend speelveld",
232
"lobby.shrinkHint": "Na elk ingesteld aantal dagen wordt de buitenste ring bij de dagelijkse uitdeling onbegaanbaar. Spelers die erop staan verliezen een leven en worden naar binnen geduwd.",
233
"lobby.shrinkDays": "Dagen tussen krimp",
234
"lobby.shrinkDaysHint": "De eerste krimp na dit aantal middernachten, daarna opnieuw telkens na evenveel dagen, tot het veld zijn minimumgrootte heeft.",
235
"lobby.ceasefire": "Gedwongen staakt-het-vuren",
236
"lobby.ceasefireHint": "In deze uren (Europe/Amsterdam) mag niemand schieten. Verplaatsen, actiepunten geven en bereik upgraden blijft toegestaan. Periodes mogen over middernacht lopen.",
237
"lobby.ceasefireAdd": "Periode toevoegen",
238
"lobby.ceasefireRemove": "Verwijderen",
239
"lobby.ceasefireStart": "Van",
240
"lobby.ceasefireEnd": "Tot",
241
"lobby.ceasefireEmpty": "Nog geen periodes. Voeg er een toe, of sleep een stuk op de klok.",
242
"lobby.ceasefireClock": "24-uursklok. Sleep de handvatten of teken een stuk; rood is staakt-het-vuren, goud is vrij schieten. Tijden zijn Europe/Amsterdam.",
243
"lobby.waiting": "Wachten tot de host het spel start.",
244
"lobby.back": "Terug",
245
"lobby.code": "Code",
246
"lobby.playerCount.one": "{n} speler",
247
"lobby.playerCount.other": "{n} spelers",
248
"lobby.playerCount.few": "{n} spelers",
249
"lobby.playerCount.many": "{n} spelers",
250
"game.day": "Dag {n}",
251
"game.nextAp": "Volgende actiepunten",
252
"game.lives": "Levens",
253
"game.ap": "Actiepunten",
254
"game.range": "Bereik",
255
"game.you": "Jij",
256
"game.dead": "Uitgeschakeld",
257
"game.surrendered": "Overgegeven",
258
"game.winner": "{name} wint!",
259
"game.youWin": "Jij wint!",
260
"game.draw": "Het spel eindigt in een gelijkspel.",
261
"game.shrinkIn": "Het veld krimpt over {n} dagen",
262
"game.shrinkInDays.one": "Het veld krimpt over {n} dag",
263
"game.shrinkInDays.other": "Het veld krimpt over {n} dagen",
264
"game.shrinkInDays.few": "Het veld krimpt over {n} dagen",
265
"game.shrinkInDays.many": "Het veld krimpt over {n} dagen",
266
"game.shrinkTomorrow": "Het veld krimpt morgen",
267
"game.shrinkToday": "Het veld krimpt bij de volgende uitdeling",
268
"game.upgrade": "Bereik vergroten",
269
"game.settings": "Instellingen",
270
"game.surrender": "Overgeven",
271
"game.surrenderConfirm": "Overgeven? Je bent dan uit dit spel. Dit kun je niet ongedaan maken.",
272
"game.surrenderConfirmBtn": "Ja, overgeven",
273
"game.surrenderCancel": "Annuleren",
274
"game.back": "Terug naar het menu",
275
"game.spectating": "Je bent uitgeschakeld. Je kunt nog meekijken, berichten sturen en, als de jury aan staat, stemmen.",
276
"game.ceasefireLeft": "Tijd over in het staakt-het-vuren",
277
"game.ceasefireUntil": "Tijd tot het staakt-het-vuren",
278
"game.ceasefireActive": "Staakt-het-vuren",
279
"game.attackDisabled": "Aanvallen",
280
"game.attackDisabledReason": "Aanvallen is niet toegestaan tijdens het staakt-het-vuren.",
281
"game.selectSelf": "Jouw tank is geselecteerd. Tik op een gemarkeerd vakje om te bewegen, of vergroot je bereik.",
282
"game.impassable": "Onbegaanbaar",
283
"game.willShrink": "Deze ring krimpt als volgende",
284
"opt.info": "Info",
285
"opt.attack": "Aanvallen",
286
"opt.give": "Actiepunten geven",
287
"opt.message": "Bericht sturen",
288
"opt.close": "Sluiten",
289
"info.title": "Info",
290
"info.lives": "Levens",
291
"info.ap": "Actiepunten",
292
"info.range": "Bereik",
293
"info.notes": "Jouw privénotities",
294
"info.notesHint": "Alleen jij ziet deze notities. Ze worden bij jouw account bewaard.",
295
"info.saveNotes": "Notities opslaan",
296
"info.saved": "Opgeslagen",
297
"give.title": "Actiepunten geven",
298
"give.howMany": "Hoeveel?",
299
"give.send": "Geven",
300
"give.youHave": "Je hebt er {n}.",
301
"chat.title": "Bericht aan {name}",
302
"chat.placeholder": "Schrijf een privébericht…",
303
"chat.send": "Versturen",
304
"chat.empty": "Nog geen berichten.",
305
"jury.title": "Jury",
306
"jury.hint": "Stem op één levende speler. Wie de meeste stemmen krijgt, ontvangt een extra actiepunt bij de volgende uitdeling. Je kunt je stem tot dan toe wijzigen. Andere spelers zien je stem niet.",
307
"jury.vote": "Stemmen",
308
"jury.votedFor": "Je stemde op {name}",
309
"jury.change": "Stem wijzigen",
310
"timeline.play": "Afspelen",
311
"timeline.pause": "Pauzeren",
312
"timeline.live": "Live",
313
"timeline.event.start": "Het spel begint",
314
"timeline.event.move": "{name} verplaatst zich",
315
"timeline.event.shoot": "{name} schiet op {target}",
316
"timeline.event.give": "{name} geeft {n} actiepunt(en) aan {target}",
317
"timeline.event.upgrade": "{name} vergroot het bereik naar {n}",
318
"timeline.event.surrender": "{name} geeft zich over",
319
"timeline.event.daily": "Dag {n}: actiepunten worden uitgedeeld",
320
"timeline.event.jury": "De jury kent een bonus toe aan {name}",
321
"timeline.event.juryTie": "De jury kent een bonus toe aan {names}",
322
"timeline.event.shrink": "Het speelveld krimpt",
323
"timeline.event.win": "{name} wint",
324
"timeline.event.death": "{name} is uitgeschakeld",
325
"timeline.event.deathShot": "{name} wordt neergeschoten door {by}",
326
"timeline.event.deathShrink": "{name} wordt geraakt door het krimpende veld",
327
"timeline.event.deathCrushed": "{name} wordt vermorzeld: geen vrij vakje meer",
328
"timeline.event.draw": "Het spel eindigt in een gelijkspel",
329
"auth.unavailable": "Inloggen is tijdelijk niet beschikbaar.",
330
"auth.backToGame": "Terug naar Allianties",
331
"auth.failed": "Inloggen is mislukt.",
332
"auth.retry": "Opnieuw proberen",
333
"auth.back": "Terug",
334
"lang.choose": "Kies een taal",
335
"lang.current": "Taal: {name}",
336
"error.login": "Log in om verder te gaan.",
337
"error.csrf": "Je sessie is verlopen. Vernieuw de pagina en probeer het opnieuw.",
338
"error.not_host": "Alleen de host kan dat doen.",
339
"error.min_players": "Je hebt minstens twee spelers nodig om te starten.",
340
"error.not_in_game": "Je zit niet in dit spel.",
341
"error.dead": "Je bent uit dit spel.",
342
"error.no_ap": "Je hebt geen actiepunten meer.",
343
"error.occupied": "Dat vakje is bezet.",
344
"error.impassable": "Dat vakje is onbegaanbaar.",
345
"error.out_of_range": "Die speler is buiten bereik.",
346
"error.invalid_move": "Die zet is niet toegestaan.",
347
"error.game_started": "Dit spel is al begonnen.",
348
"error.game_finished": "Dit spel is afgelopen.",
349
"error.lobby_full": "Deze lobby is vol.",
350
"error.unknown_code": "Geen lobby gevonden met die code.",
351
"error.cannot_vote": "Je kunt nu niet stemmen.",
352
"error.bad_vote": "Je kunt alleen op een levende speler stemmen.",
353
"error.bad_give": "Zoveel actiepunten kun je niet geven.",
354
"error.unknown_action": "Onbekende actie.",
355
"error.ceasefire": "Je kunt niet aanvallen tijdens het staakt-het-vuren.",
356
"error.generic": "Er ging iets mis. Probeer het opnieuw.",
357
"error.serverStatus": "De server gaf {status}.",
358
}
359
360
# For the other 8 languages I'll define complete dicts similarly.
361
# To keep this file maintainable, remaining locales are written in full below.
362
363
def load_rest():
364
# Imported from the second half written alongside this script's execution
365
# via the REST dicts defined after this function in the same file — we
366
# actually just put them as globals below.
367
pass
368
369
# The remaining translations are large; they follow in gen_i18n_rest and get merged.
370
# For a first complete catalog, if a locale is missing a key we fail.
371
372
LOCALES_ORDER = ["en", "nl", "de", "fr", "ja", "zh", "ko", "pl", "ru", "es"]
373
374
# Placeholder: filled by gen_i18n_rest.py or the section below.
375
REST = {}
376
377
if __name__ == "__main__":
378
print("partial generator — use the full script")
@@ -0,0 +1,378 @@1
#!/usr/bin/env python32
"""Generate server/lib/i18n.json for Allianties (10 locales, identical keys)."""3
import json4
from pathlib import Path5
6
# The game name is never translated.7
NAME = "Allianties"8
9
# English is the source of truth. Every other locale must have the same keys.10
EN = {11
"app.name": NAME,12
"menu.tagline": "A game of patience, alliances and well-timed shots.",13
"menu.login": "Log in",14
"menu.logout": "Log out",15
"menu.loggedInAs": "Logged in as",16
"menu.localTest": "local test:",17
"menu.create": "New lobby",18
"menu.join": "Join",19
"menu.codePlaceholder": "Code",20
"menu.myGames": "Your games",21
"menu.noGames": "You have no games yet. Start a lobby and invite others.",22
"menu.authUnconfiguredHtml": "Sign-in is not set up on this server yet. The callback <code>/allianties/callback.php</code> must be registered at auth.timfalken.com, and the client secret must be configured.",23
"menu.guestHint": "Log in to create a lobby, invite players and start a lasting game.",24
"menu.open": "Open",25
"menu.continue": "Continue",26
"menu.statusLobby": "Lobby",27
"menu.statusRunning": "In play",28
"menu.statusFinished": "Finished",29
"menu.youWon": "You won",30
"menu.draw": "Draw",31
"menu.winnerIs": "Winner: {name}",32
"menu.needLogin": "Log in first to play.",33
"menu.players": "Players",34
35
"lobby.title": "Lobby",36
"lobby.invite": "Invite",37
"lobby.copy": "Copy link",38
"lobby.copied": "Copied",39
"lobby.shareHint": "Share this code or link. Players log in and join.",40
"lobby.players": "Players",41
"lobby.start": "Start game",42
"lobby.leave": "Leave lobby",43
"lobby.host": "Host",44
"lobby.you": "you",45
"lobby.minPlayers": "You need at least two players to start.",46
"lobby.needTwo": "Waiting for at least one more player…",47
"lobby.rules": "Rules",48
"lobby.jury": "Jury",49
"lobby.juryHint": "Dead players vote each day for a living player. The player with the most votes receives one extra action point at the next daily distribution. Ties: every tied player receives the bonus. Votes are secret and can be changed until then.",50
"lobby.shrink": "Shrinking arena",51
"lobby.shrinkHint": "After every set number of days, the outer ring becomes impassable at the daily distribution. Players standing on it lose one life and are pushed inward.",52
"lobby.shrinkDays": "Days between shrinks",53
"lobby.shrinkDaysHint": "First shrink after this many midnights, then again each time that many days pass, until the arena reaches its minimum size.",54
"lobby.ceasefire": "Forced cease-fire hours",55
"lobby.ceasefireHint": "During these hours (Europe/Amsterdam) no one may shoot. Moving, giving action points and upgrading range remain allowed. Periods may wrap around midnight.",56
"lobby.ceasefireAdd": "Add period",57
"lobby.ceasefireRemove": "Remove",58
"lobby.ceasefireStart": "From",59
"lobby.ceasefireEnd": "Until",60
"lobby.ceasefireEmpty": "No periods yet. Add one, or drag a slice on the clock.",61
"lobby.ceasefireClock": "24-hour clock. Drag the handles or paint a slice; red is cease-fire, gold is open fire. Times are Europe/Amsterdam.",62
"lobby.waiting": "Waiting for the host to start the game.",63
"lobby.back": "Back",64
"lobby.code": "Code",65
"lobby.playerCount.one": "{n} player",66
"lobby.playerCount.other": "{n} players",67
"lobby.playerCount.few": "{n} players",68
"lobby.playerCount.many": "{n} players",69
70
"game.day": "Day {n}",71
"game.nextAp": "Next action points",72
"game.lives": "Lives",73
"game.ap": "Action points",74
"game.range": "Range",75
"game.you": "You",76
"game.dead": "Out",77
"game.surrendered": "Surrendered",78
"game.winner": "{name} wins!",79
"game.youWin": "You win!",80
"game.draw": "The game ends in a draw.",81
"game.shrinkIn": "Arena shrinks in {n} days",82
"game.shrinkInDays.one": "Arena shrinks in {n} day",83
"game.shrinkInDays.other": "Arena shrinks in {n} days",84
"game.shrinkInDays.few": "Arena shrinks in {n} days",85
"game.shrinkInDays.many": "Arena shrinks in {n} days",86
"game.shrinkTomorrow": "Arena shrinks tomorrow",87
"game.shrinkToday": "Arena shrinks at the next distribution",88
"game.upgrade": "Upgrade range",89
"game.settings": "Settings",90
"game.surrender": "Surrender",91
"game.surrenderConfirm": "Surrender? You will be out of this game. This cannot be undone.",92
"game.surrenderConfirmBtn": "Yes, surrender",93
"game.surrenderCancel": "Cancel",94
"game.back": "Back to menu",95
"game.spectating": "You are out. You can still watch, send messages and, if the jury is on, vote.",96
"game.ceasefireLeft": "Time left in cease-fire",97
"game.ceasefireUntil": "Time until cease-fire",98
"game.ceasefireActive": "Cease-fire",99
"game.attackDisabled": "Attack",100
"game.attackDisabledReason": "Attack is not allowed during cease-fire hours.",101
"game.selectSelf": "Your tank is selected. Tap a highlighted tile to move, or upgrade your range.",102
"game.impassable": "Impassable",103
"game.willShrink": "This ring will shrink next",104
105
"opt.info": "Info",106
"opt.attack": "Attack",107
"opt.give": "Give action points",108
"opt.message": "Send message",109
"opt.close": "Close",110
111
"info.title": "Info",112
"info.lives": "Lives",113
"info.ap": "Action points",114
"info.range": "Range",115
"info.notes": "Your private notes",116
"info.notesHint": "Only you can see these notes. They are stored with your account.",117
"info.saveNotes": "Save notes",118
"info.saved": "Saved",119
120
"give.title": "Give action points",121
"give.howMany": "How many?",122
"give.send": "Give",123
"give.youHave": "You have {n}.",124
125
"chat.title": "Message {name}",126
"chat.placeholder": "Write a private message…",127
"chat.send": "Send",128
"chat.empty": "No messages yet.",129
130
"jury.title": "Jury",131
"jury.hint": "Vote for one living player. The player with the most votes gets an extra action point at the next distribution. You can change your vote until then. Other players cannot see your vote.",132
"jury.vote": "Vote",133
"jury.votedFor": "You voted for {name}",134
"jury.change": "Change vote",135
136
"timeline.play": "Play",137
"timeline.pause": "Pause",138
"timeline.live": "Live",139
"timeline.event.start": "The game begins",140
"timeline.event.move": "{name} moves",141
"timeline.event.shoot": "{name} shoots {target}",142
"timeline.event.give": "{name} gives {n} action point(s) to {target}",143
"timeline.event.upgrade": "{name} upgrades range to {n}",144
"timeline.event.surrender": "{name} surrenders",145
"timeline.event.daily": "Day {n}: action points are distributed",146
"timeline.event.jury": "The jury awards a bonus to {name}",147
"timeline.event.juryTie": "The jury awards a bonus to {names}",148
"timeline.event.shrink": "The arena shrinks",149
"timeline.event.win": "{name} wins",150
"timeline.event.death": "{name} is out",151
"timeline.event.deathShot": "{name} is shot by {by}",152
"timeline.event.deathShrink": "{name} is caught by the shrinking arena",153
"timeline.event.deathCrushed": "{name} is crushed: no free tile left",154
"timeline.event.draw": "The game ends in a draw",155
156
"auth.unavailable": "Sign-in is temporarily unavailable.",157
"auth.backToGame": "Back to Allianties",158
"auth.failed": "Sign-in failed.",159
"auth.retry": "Try again",160
"auth.back": "Back",161
162
"lang.choose": "Choose language",163
"lang.current": "Language: {name}",164
165
"error.login": "Log in to continue.",166
"error.csrf": "Your session expired. Refresh the page and try again.",167
"error.not_host": "Only the host can do that.",168
"error.min_players": "You need at least two players to start.",169
"error.not_in_game": "You are not in this game.",170
"error.dead": "You are out of this game.",171
"error.no_ap": "You have no action points left.",172
"error.occupied": "That tile is occupied.",173
"error.impassable": "That tile is impassable.",174
"error.out_of_range": "That player is out of range.",175
"error.invalid_move": "That move is not allowed.",176
"error.game_started": "This game has already started.",177
"error.game_finished": "This game is over.",178
"error.lobby_full": "This lobby is full.",179
"error.unknown_code": "No lobby found with that code.",180
"error.cannot_vote": "You cannot vote now.",181
"error.bad_vote": "You can only vote for a living player.",182
"error.bad_give": "You cannot give that many action points.",183
"error.unknown_action": "Unknown action.",184
"error.ceasefire": "You cannot attack during cease-fire hours.",185
"error.generic": "Something went wrong. Please try again.",186
"error.serverStatus": "The server returned {status}.",187
}188
189
# Translations. Every locale must include every EN key.190
# "Allianties" stays Allianties everywhere.191
192
NL = {193
"app.name": NAME,194
"menu.tagline": "Een spel van geduld, allianties en goed getimede schoten.",195
"menu.login": "Inloggen",196
"menu.logout": "Uitloggen",197
"menu.loggedInAs": "Ingelogd als",198
"menu.localTest": "lokale test:",199
"menu.create": "Nieuwe lobby",200
"menu.join": "Deelnemen",201
"menu.codePlaceholder": "Code",202
"menu.myGames": "Jouw spellen",203
"menu.noGames": "Je hebt nog geen spellen. Start een lobby en nodig anderen uit.",204
"menu.authUnconfiguredHtml": "Inloggen is op deze server nog niet ingesteld. De callback <code>/allianties/callback.php</code> moet bij auth.timfalken.com worden geregistreerd, en het clientgeheim moet worden gezet.",205
"menu.guestHint": "Log in om een lobby te maken, spelers uit te nodigen en een blijvend spel te starten.",206
"menu.open": "Openen",207
"menu.continue": "Verder",208
"menu.statusLobby": "Lobby",209
"menu.statusRunning": "Bezig",210
"menu.statusFinished": "Afgelopen",211
"menu.youWon": "Jij won",212
"menu.draw": "Gelijkspel",213
"menu.winnerIs": "Winnaar: {name}",214
"menu.needLogin": "Log eerst in om te spelen.",215
"menu.players": "Spelers",216
"lobby.title": "Lobby",217
"lobby.invite": "Uitnodigen",218
"lobby.copy": "Kopieer link",219
"lobby.copied": "Gekopieerd",220
"lobby.shareHint": "Deel deze code of link. Spelers loggen in en doen mee.",221
"lobby.players": "Spelers",222
"lobby.start": "Start spel",223
"lobby.leave": "Lobby verlaten",224
"lobby.host": "Host",225
"lobby.you": "jij",226
"lobby.minPlayers": "Je hebt minstens twee spelers nodig om te starten.",227
"lobby.needTwo": "Wachten op minstens één speler extra…",228
"lobby.rules": "Regels",229
"lobby.jury": "Jury",230
"lobby.juryHint": "Dode spelers stemmen elke dag op een levende speler. Wie de meeste stemmen krijgt, ontvangt één extra actiepunt bij de volgende dagelijkse uitdeling. Bij een gelijke stand krijgt iedere gelijkstaande speler de bonus. Stemmen zijn geheim en tot dan toe te wijzigen.",231
"lobby.shrink": "Krimpend speelveld",232
"lobby.shrinkHint": "Na elk ingesteld aantal dagen wordt de buitenste ring bij de dagelijkse uitdeling onbegaanbaar. Spelers die erop staan verliezen een leven en worden naar binnen geduwd.",233
"lobby.shrinkDays": "Dagen tussen krimp",234
"lobby.shrinkDaysHint": "De eerste krimp na dit aantal middernachten, daarna opnieuw telkens na evenveel dagen, tot het veld zijn minimumgrootte heeft.",235
"lobby.ceasefire": "Gedwongen staakt-het-vuren",236
"lobby.ceasefireHint": "In deze uren (Europe/Amsterdam) mag niemand schieten. Verplaatsen, actiepunten geven en bereik upgraden blijft toegestaan. Periodes mogen over middernacht lopen.",237
"lobby.ceasefireAdd": "Periode toevoegen",238
"lobby.ceasefireRemove": "Verwijderen",239
"lobby.ceasefireStart": "Van",240
"lobby.ceasefireEnd": "Tot",241
"lobby.ceasefireEmpty": "Nog geen periodes. Voeg er een toe, of sleep een stuk op de klok.",242
"lobby.ceasefireClock": "24-uursklok. Sleep de handvatten of teken een stuk; rood is staakt-het-vuren, goud is vrij schieten. Tijden zijn Europe/Amsterdam.",243
"lobby.waiting": "Wachten tot de host het spel start.",244
"lobby.back": "Terug",245
"lobby.code": "Code",246
"lobby.playerCount.one": "{n} speler",247
"lobby.playerCount.other": "{n} spelers",248
"lobby.playerCount.few": "{n} spelers",249
"lobby.playerCount.many": "{n} spelers",250
"game.day": "Dag {n}",251
"game.nextAp": "Volgende actiepunten",252
"game.lives": "Levens",253
"game.ap": "Actiepunten",254
"game.range": "Bereik",255
"game.you": "Jij",256
"game.dead": "Uitgeschakeld",257
"game.surrendered": "Overgegeven",258
"game.winner": "{name} wint!",259
"game.youWin": "Jij wint!",260
"game.draw": "Het spel eindigt in een gelijkspel.",261
"game.shrinkIn": "Het veld krimpt over {n} dagen",262
"game.shrinkInDays.one": "Het veld krimpt over {n} dag",263
"game.shrinkInDays.other": "Het veld krimpt over {n} dagen",264
"game.shrinkInDays.few": "Het veld krimpt over {n} dagen",265
"game.shrinkInDays.many": "Het veld krimpt over {n} dagen",266
"game.shrinkTomorrow": "Het veld krimpt morgen",267
"game.shrinkToday": "Het veld krimpt bij de volgende uitdeling",268
"game.upgrade": "Bereik vergroten",269
"game.settings": "Instellingen",270
"game.surrender": "Overgeven",271
"game.surrenderConfirm": "Overgeven? Je bent dan uit dit spel. Dit kun je niet ongedaan maken.",272
"game.surrenderConfirmBtn": "Ja, overgeven",273
"game.surrenderCancel": "Annuleren",274
"game.back": "Terug naar het menu",275
"game.spectating": "Je bent uitgeschakeld. Je kunt nog meekijken, berichten sturen en, als de jury aan staat, stemmen.",276
"game.ceasefireLeft": "Tijd over in het staakt-het-vuren",277
"game.ceasefireUntil": "Tijd tot het staakt-het-vuren",278
"game.ceasefireActive": "Staakt-het-vuren",279
"game.attackDisabled": "Aanvallen",280
"game.attackDisabledReason": "Aanvallen is niet toegestaan tijdens het staakt-het-vuren.",281
"game.selectSelf": "Jouw tank is geselecteerd. Tik op een gemarkeerd vakje om te bewegen, of vergroot je bereik.",282
"game.impassable": "Onbegaanbaar",283
"game.willShrink": "Deze ring krimpt als volgende",284
"opt.info": "Info",285
"opt.attack": "Aanvallen",286
"opt.give": "Actiepunten geven",287
"opt.message": "Bericht sturen",288
"opt.close": "Sluiten",289
"info.title": "Info",290
"info.lives": "Levens",291
"info.ap": "Actiepunten",292
"info.range": "Bereik",293
"info.notes": "Jouw privénotities",294
"info.notesHint": "Alleen jij ziet deze notities. Ze worden bij jouw account bewaard.",295
"info.saveNotes": "Notities opslaan",296
"info.saved": "Opgeslagen",297
"give.title": "Actiepunten geven",298
"give.howMany": "Hoeveel?",299
"give.send": "Geven",300
"give.youHave": "Je hebt er {n}.",301
"chat.title": "Bericht aan {name}",302
"chat.placeholder": "Schrijf een privébericht…",303
"chat.send": "Versturen",304
"chat.empty": "Nog geen berichten.",305
"jury.title": "Jury",306
"jury.hint": "Stem op één levende speler. Wie de meeste stemmen krijgt, ontvangt een extra actiepunt bij de volgende uitdeling. Je kunt je stem tot dan toe wijzigen. Andere spelers zien je stem niet.",307
"jury.vote": "Stemmen",308
"jury.votedFor": "Je stemde op {name}",309
"jury.change": "Stem wijzigen",310
"timeline.play": "Afspelen",311
"timeline.pause": "Pauzeren",312
"timeline.live": "Live",313
"timeline.event.start": "Het spel begint",314
"timeline.event.move": "{name} verplaatst zich",315
"timeline.event.shoot": "{name} schiet op {target}",316
"timeline.event.give": "{name} geeft {n} actiepunt(en) aan {target}",317
"timeline.event.upgrade": "{name} vergroot het bereik naar {n}",318
"timeline.event.surrender": "{name} geeft zich over",319
"timeline.event.daily": "Dag {n}: actiepunten worden uitgedeeld",320
"timeline.event.jury": "De jury kent een bonus toe aan {name}",321
"timeline.event.juryTie": "De jury kent een bonus toe aan {names}",322
"timeline.event.shrink": "Het speelveld krimpt",323
"timeline.event.win": "{name} wint",324
"timeline.event.death": "{name} is uitgeschakeld",325
"timeline.event.deathShot": "{name} wordt neergeschoten door {by}",326
"timeline.event.deathShrink": "{name} wordt geraakt door het krimpende veld",327
"timeline.event.deathCrushed": "{name} wordt vermorzeld: geen vrij vakje meer",328
"timeline.event.draw": "Het spel eindigt in een gelijkspel",329
"auth.unavailable": "Inloggen is tijdelijk niet beschikbaar.",330
"auth.backToGame": "Terug naar Allianties",331
"auth.failed": "Inloggen is mislukt.",332
"auth.retry": "Opnieuw proberen",333
"auth.back": "Terug",334
"lang.choose": "Kies een taal",335
"lang.current": "Taal: {name}",336
"error.login": "Log in om verder te gaan.",337
"error.csrf": "Je sessie is verlopen. Vernieuw de pagina en probeer het opnieuw.",338
"error.not_host": "Alleen de host kan dat doen.",339
"error.min_players": "Je hebt minstens twee spelers nodig om te starten.",340
"error.not_in_game": "Je zit niet in dit spel.",341
"error.dead": "Je bent uit dit spel.",342
"error.no_ap": "Je hebt geen actiepunten meer.",343
"error.occupied": "Dat vakje is bezet.",344
"error.impassable": "Dat vakje is onbegaanbaar.",345
"error.out_of_range": "Die speler is buiten bereik.",346
"error.invalid_move": "Die zet is niet toegestaan.",347
"error.game_started": "Dit spel is al begonnen.",348
"error.game_finished": "Dit spel is afgelopen.",349
"error.lobby_full": "Deze lobby is vol.",350
"error.unknown_code": "Geen lobby gevonden met die code.",351
"error.cannot_vote": "Je kunt nu niet stemmen.",352
"error.bad_vote": "Je kunt alleen op een levende speler stemmen.",353
"error.bad_give": "Zoveel actiepunten kun je niet geven.",354
"error.unknown_action": "Onbekende actie.",355
"error.ceasefire": "Je kunt niet aanvallen tijdens het staakt-het-vuren.",356
"error.generic": "Er ging iets mis. Probeer het opnieuw.",357
"error.serverStatus": "De server gaf {status}.",358
}359
360
# For the other 8 languages I'll define complete dicts similarly.361
# To keep this file maintainable, remaining locales are written in full below.362
363
def load_rest():364
# Imported from the second half written alongside this script's execution365
# via the REST dicts defined after this function in the same file — we366
# actually just put them as globals below.367
pass368
369
# The remaining translations are large; they follow in gen_i18n_rest and get merged.370
# For a first complete catalog, if a locale is missing a key we fail.371
372
LOCALES_ORDER = ["en", "nl", "de", "fr", "ja", "zh", "ko", "pl", "ru", "es"]373
374
# Placeholder: filled by gen_i18n_rest.py or the section below.375
REST = {}376
377
if __name__ == "__main__":378
print("partial generator — use the full script")@@ -0,0 +1,1346 @@
1
# -*- coding: utf-8 -*-
2
NAME = "Allianties"
3
4
DE = {
5
"app.name": NAME,
6
"menu.tagline": "Ein Spiel aus Geduld, Allianzen und gut getimten Schüssen.",
7
"menu.login": "Anmelden",
8
"menu.logout": "Abmelden",
9
"menu.loggedInAs": "Angemeldet als",
10
"menu.localTest": "lokaler Test:",
11
"menu.create": "Neue Lobby",
12
"menu.join": "Beitreten",
13
"menu.codePlaceholder": "Code",
14
"menu.myGames": "Deine Spiele",
15
"menu.noGames": "Du hast noch keine Spiele. Eröffne eine Lobby und lade andere ein.",
16
"menu.authUnconfiguredHtml": "Die Anmeldung ist auf diesem Server noch nicht eingerichtet. Der Callback <code>/allianties/callback.php</code> muss bei auth.timfalken.com registriert und das Client-Geheimnis konfiguriert werden.",
17
"menu.guestHint": "Melde dich an, um eine Lobby zu erstellen, Spieler einzuladen und ein dauerhaftes Spiel zu starten.",
18
"menu.open": "Öffnen",
19
"menu.continue": "Weiter",
20
"menu.statusLobby": "Lobby",
21
"menu.statusRunning": "Läuft",
22
"menu.statusFinished": "Beendet",
23
"menu.youWon": "Du hast gewonnen",
24
"menu.draw": "Unentschieden",
25
"menu.winnerIs": "Gewinner: {name}",
26
"menu.needLogin": "Melde dich zuerst an, um zu spielen.",
27
"menu.players": "Spieler",
28
"lobby.title": "Lobby",
29
"lobby.invite": "Einladen",
30
"lobby.copy": "Link kopieren",
31
"lobby.copied": "Kopiert",
32
"lobby.shareHint": "Teile diesen Code oder Link. Spieler melden sich an und treten bei.",
33
"lobby.players": "Spieler",
34
"lobby.start": "Spiel starten",
35
"lobby.leave": "Lobby verlassen",
36
"lobby.host": "Gastgeber",
37
"lobby.you": "du",
38
"lobby.minPlayers": "Du brauchst mindestens zwei Spieler, um zu starten.",
39
"lobby.needTwo": "Warte auf mindestens einen weiteren Spieler…",
40
"lobby.rules": "Regeln",
41
"lobby.jury": "Jury",
42
"lobby.juryHint": "Tote Spieler stimmen täglich für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten täglichen Verteilung einen Extra-Aktionspunkt. Bei Gleichstand erhält jeder gleichauf liegende Spieler den Bonus. Stimmen sind geheim und bis dahin änderbar.",
43
"lobby.shrink": "Schrumpfendes Spielfeld",
44
"lobby.shrinkHint": "Nach einer festgelegten Anzahl von Tagen wird der äußere Ring bei der täglichen Verteilung unpassierbar. Spieler, die darauf stehen, verlieren ein Leben und werden nach innen geschoben.",
45
"lobby.shrinkDays": "Tage zwischen Schrumpfungen",
46
"lobby.shrinkDaysHint": "Erste Schrumpfung nach so vielen Mitternächten, danach erneut nach jeweils ebenso vielen Tagen, bis das Feld seine Mindestgröße erreicht.",
47
"lobby.ceasefire": "Erzwungene Waffenruhe",
48
"lobby.ceasefireHint": "In diesen Stunden (Europe/Amsterdam) darf niemand schießen. Bewegen, Aktionspunkte abgeben und die Reichweite erhöhen bleiben erlaubt. Zeiträume dürfen über Mitternacht gehen.",
49
"lobby.ceasefireAdd": "Zeitraum hinzufügen",
50
"lobby.ceasefireRemove": "Entfernen",
51
"lobby.ceasefireStart": "Von",
52
"lobby.ceasefireEnd": "Bis",
53
"lobby.ceasefireEmpty": "Noch keine Zeiträume. Füge einen hinzu oder ziehe ein Segment auf der Uhr.",
54
"lobby.ceasefireClock": "24-Stunden-Uhr. Ziehe die Griffe oder male ein Segment; rot ist Waffenruhe, gold ist Feuer frei. Zeiten sind Europe/Amsterdam.",
55
"lobby.waiting": "Warte, bis der Gastgeber das Spiel startet.",
56
"lobby.back": "Zurück",
57
"lobby.code": "Code",
58
"lobby.playerCount.one": "{n} Spieler",
59
"lobby.playerCount.other": "{n} Spieler",
60
"lobby.playerCount.few": "{n} Spieler",
61
"lobby.playerCount.many": "{n} Spieler",
62
"game.day": "Tag {n}",
63
"game.nextAp": "Nächste Aktionspunkte",
64
"game.lives": "Leben",
65
"game.ap": "Aktionspunkte",
66
"game.range": "Reichweite",
67
"game.you": "Du",
68
"game.dead": "Ausgeschieden",
69
"game.surrendered": "Aufgegeben",
70
"game.winner": "{name} gewinnt!",
71
"game.youWin": "Du gewinnst!",
72
"game.draw": "Das Spiel endet unentschieden.",
73
"game.shrinkIn": "Das Feld schrumpft in {n} Tagen",
74
"game.shrinkInDays.one": "Das Feld schrumpft in {n} Tag",
75
"game.shrinkInDays.other": "Das Feld schrumpft in {n} Tagen",
76
"game.shrinkInDays.few": "Das Feld schrumpft in {n} Tagen",
77
"game.shrinkInDays.many": "Das Feld schrumpft in {n} Tagen",
78
"game.shrinkTomorrow": "Das Feld schrumpft morgen",
79
"game.shrinkToday": "Das Feld schrumpft bei der nächsten Verteilung",
80
"game.upgrade": "Reichweite erhöhen",
81
"game.settings": "Einstellungen",
82
"game.surrender": "Aufgeben",
83
"game.surrenderConfirm": "Aufgeben? Du scheidest aus diesem Spiel aus. Das lässt sich nicht rückgängig machen.",
84
"game.surrenderConfirmBtn": "Ja, aufgeben",
85
"game.surrenderCancel": "Abbrechen",
86
"game.back": "Zurück zum Menü",
87
"game.spectating": "Du bist ausgeschieden. Du kannst weiterhin zuschauen, Nachrichten senden und, wenn die Jury an ist, abstimmen.",
88
"game.ceasefireLeft": "Verbleibende Waffenruhe",
89
"game.ceasefireUntil": "Zeit bis zur Waffenruhe",
90
"game.ceasefireActive": "Waffenruhe",
91
"game.attackDisabled": "Angreifen",
92
"game.attackDisabledReason": "Angreifen ist während der Waffenruhe nicht erlaubt.",
93
"game.selectSelf": "Dein Panzer ist ausgewählt. Tippe auf ein markiertes Feld, um dich zu bewegen, oder erhöhe deine Reichweite.",
94
"game.impassable": "Unpassierbar",
95
"game.willShrink": "Dieser Ring schrumpft als Nächstes",
96
"opt.info": "Info",
97
"opt.attack": "Angreifen",
98
"opt.give": "Aktionspunkte geben",
99
"opt.message": "Nachricht senden",
100
"opt.close": "Schließen",
101
"info.title": "Info",
102
"info.lives": "Leben",
103
"info.ap": "Aktionspunkte",
104
"info.range": "Reichweite",
105
"info.notes": "Deine privaten Notizen",
106
"info.notesHint": "Nur du kannst diese Notizen sehen. Sie werden bei deinem Konto gespeichert.",
107
"info.saveNotes": "Notizen speichern",
108
"info.saved": "Gespeichert",
109
"give.title": "Aktionspunkte geben",
110
"give.howMany": "Wie viele?",
111
"give.send": "Geben",
112
"give.youHave": "Du hast {n}.",
113
"chat.title": "Nachricht an {name}",
114
"chat.placeholder": "Schreibe eine private Nachricht…",
115
"chat.send": "Senden",
116
"chat.empty": "Noch keine Nachrichten.",
117
"jury.title": "Jury",
118
"jury.hint": "Stimme für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten Verteilung einen Extra-Aktionspunkt. Du kannst deine Stimme bis dahin ändern. Andere Spieler sehen deine Stimme nicht.",
119
"jury.vote": "Abstimmen",
120
"jury.votedFor": "Du hast für {name} gestimmt",
121
"jury.change": "Stimme ändern",
122
"timeline.play": "Abspielen",
123
"timeline.pause": "Pause",
124
"timeline.live": "Live",
125
"timeline.event.start": "Das Spiel beginnt",
126
"timeline.event.move": "{name} bewegt sich",
127
"timeline.event.shoot": "{name} schießt auf {target}",
128
"timeline.event.give": "{name} gibt {n} Aktionspunkt(e) an {target}",
129
"timeline.event.upgrade": "{name} erhöht die Reichweite auf {n}",
130
"timeline.event.surrender": "{name} gibt auf",
131
"timeline.event.daily": "Tag {n}: Aktionspunkte werden verteilt",
132
"timeline.event.jury": "Die Jury vergibt einen Bonus an {name}",
133
"timeline.event.juryTie": "Die Jury vergibt einen Bonus an {names}",
134
"timeline.event.shrink": "Das Spielfeld schrumpft",
135
"timeline.event.win": "{name} gewinnt",
136
"timeline.event.death": "{name} scheidet aus",
137
"timeline.event.deathShot": "{name} wird von {by} erschossen",
138
"timeline.event.deathShrink": "{name} wird vom schrumpfenden Feld erfasst",
139
"timeline.event.deathCrushed": "{name} wird zerdrückt: kein freies Feld mehr",
140
"timeline.event.draw": "Das Spiel endet unentschieden",
141
"auth.unavailable": "Die Anmeldung ist vorübergehend nicht verfügbar.",
142
"auth.backToGame": "Zurück zu Allianties",
143
"auth.failed": "Anmeldung fehlgeschlagen.",
144
"auth.retry": "Erneut versuchen",
145
"auth.back": "Zurück",
146
"lang.choose": "Sprache wählen",
147
"lang.current": "Sprache: {name}",
148
"error.login": "Melde dich an, um fortzufahren.",
149
"error.csrf": "Deine Sitzung ist abgelaufen. Aktualisiere die Seite und versuche es erneut.",
150
"error.not_host": "Das kann nur der Gastgeber tun.",
151
"error.min_players": "Du brauchst mindestens zwei Spieler, um zu starten.",
152
"error.not_in_game": "Du bist nicht in diesem Spiel.",
153
"error.dead": "Du bist aus diesem Spiel ausgeschieden.",
154
"error.no_ap": "Du hast keine Aktionspunkte mehr.",
155
"error.occupied": "Dieses Feld ist besetzt.",
156
"error.impassable": "Dieses Feld ist unpassierbar.",
157
"error.out_of_range": "Dieser Spieler ist außer Reichweite.",
158
"error.invalid_move": "Dieser Zug ist nicht erlaubt.",
159
"error.game_started": "Dieses Spiel hat bereits begonnen.",
160
"error.game_finished": "Dieses Spiel ist beendet.",
161
"error.lobby_full": "Diese Lobby ist voll.",
162
"error.unknown_code": "Keine Lobby mit diesem Code gefunden.",
163
"error.cannot_vote": "Du kannst jetzt nicht abstimmen.",
164
"error.bad_vote": "Du kannst nur für einen lebenden Spieler stimmen.",
165
"error.bad_give": "So viele Aktionspunkte kannst du nicht abgeben.",
166
"error.unknown_action": "Unbekannte Aktion.",
167
"error.ceasefire": "Während der Waffenruhe kannst du nicht angreifen.",
168
"error.generic": "Etwas ist schiefgegangen. Bitte versuche es erneut.",
169
"error.serverStatus": "Der Server antwortete mit {status}.",
170
}
171
172
FR = {
173
"app.name": NAME,
174
"menu.tagline": "Un jeu de patience, d'alliances et de tirs bien calculés.",
175
"menu.login": "Connexion",
176
"menu.logout": "Déconnexion",
177
"menu.loggedInAs": "Connecté en tant que",
178
"menu.localTest": "test local :",
179
"menu.create": "Nouveau salon",
180
"menu.join": "Rejoindre",
181
"menu.codePlaceholder": "Code",
182
"menu.myGames": "Vos parties",
183
"menu.noGames": "Vous n'avez pas encore de partie. Créez un salon et invitez d'autres joueurs.",
184
"menu.authUnconfiguredHtml": "La connexion n'est pas encore configurée sur ce serveur. Le callback <code>/allianties/callback.php</code> doit être enregistré sur auth.timfalken.com, et le secret client doit être défini.",
185
"menu.guestHint": "Connectez-vous pour créer un salon, inviter des joueurs et lancer une partie durable.",
186
"menu.open": "Ouvrir",
187
"menu.continue": "Continuer",
188
"menu.statusLobby": "Salon",
189
"menu.statusRunning": "En cours",
190
"menu.statusFinished": "Terminée",
191
"menu.youWon": "Vous avez gagné",
192
"menu.draw": "Match nul",
193
"menu.winnerIs": "Vainqueur : {name}",
194
"menu.needLogin": "Connectez-vous d'abord pour jouer.",
195
"menu.players": "Joueurs",
196
"lobby.title": "Salon",
197
"lobby.invite": "Inviter",
198
"lobby.copy": "Copier le lien",
199
"lobby.copied": "Copié",
200
"lobby.shareHint": "Partagez ce code ou ce lien. Les joueurs se connectent et rejoignent la partie.",
201
"lobby.players": "Joueurs",
202
"lobby.start": "Lancer la partie",
203
"lobby.leave": "Quitter le salon",
204
"lobby.host": "Hôte",
205
"lobby.you": "vous",
206
"lobby.minPlayers": "Il faut au moins deux joueurs pour commencer.",
207
"lobby.needTwo": "En attente d'au moins un joueur de plus…",
208
"lobby.rules": "Règles",
209
"lobby.jury": "Jury",
210
"lobby.juryHint": "Les joueurs éliminés votent chaque jour pour un joueur vivant. Celui qui recueille le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution quotidienne. En cas d'égalité, chaque joueur à égalité reçoit le bonus. Les votes sont secrets et modifiables jusque-là.",
211
"lobby.shrink": "Arène rétrécissante",
212
"lobby.shrinkHint": "Après un nombre de jours réglable, l'anneau extérieur devient infranchissable à la distribution quotidienne. Les joueurs qui s'y trouvent perdent une vie et sont poussés vers l'intérieur.",
213
"lobby.shrinkDays": "Jours entre les rétrécissements",
214
"lobby.shrinkDaysHint": "Premier rétrécissement après autant de minuits, puis de nouveau tous les autant de jours, jusqu'à la taille minimale de l'arène.",
215
"lobby.ceasefire": "Heures de cessez-le-feu forcé",
216
"lobby.ceasefireHint": "Pendant ces heures (Europe/Amsterdam), personne ne peut tirer. Se déplacer, donner des points d'action et améliorer la portée restent autorisés. Les plages peuvent chevaucher minuit.",
217
"lobby.ceasefireAdd": "Ajouter une plage",
218
"lobby.ceasefireRemove": "Supprimer",
219
"lobby.ceasefireStart": "De",
220
"lobby.ceasefireEnd": "À",
221
"lobby.ceasefireEmpty": "Aucune plage pour l'instant. Ajoutez-en une, ou dessinez un secteur sur l'horloge.",
222
"lobby.ceasefireClock": "Horloge 24 heures. Faites glisser les poignées ou dessinez un secteur ; le rouge est le cessez-le-feu, l'or le feu autorisé. Heures en Europe/Amsterdam.",
223
"lobby.waiting": "En attente que l'hôte lance la partie.",
224
"lobby.back": "Retour",
225
"lobby.code": "Code",
226
"lobby.playerCount.one": "{n} joueur",
227
"lobby.playerCount.other": "{n} joueurs",
228
"lobby.playerCount.few": "{n} joueurs",
229
"lobby.playerCount.many": "{n} joueurs",
230
"game.day": "Jour {n}",
231
"game.nextAp": "Prochains points d'action",
232
"game.lives": "Vies",
233
"game.ap": "Points d'action",
234
"game.range": "Portée",
235
"game.you": "Vous",
236
"game.dead": "Éliminé",
237
"game.surrendered": "A abandonné",
238
"game.winner": "{name} gagne !",
239
"game.youWin": "Vous gagnez !",
240
"game.draw": "La partie se termine par un match nul.",
241
"game.shrinkIn": "L'arène rétrécit dans {n} jours",
242
"game.shrinkInDays.one": "L'arène rétrécit dans {n} jour",
243
"game.shrinkInDays.other": "L'arène rétrécit dans {n} jours",
244
"game.shrinkInDays.few": "L'arène rétrécit dans {n} jours",
245
"game.shrinkInDays.many": "L'arène rétrécit dans {n} jours",
246
"game.shrinkTomorrow": "L'arène rétrécit demain",
247
"game.shrinkToday": "L'arène rétrécit à la prochaine distribution",
248
"game.upgrade": "Augmenter la portée",
249
"game.settings": "Paramètres",
250
"game.surrender": "Abandonner",
251
"game.surrenderConfirm": "Abandonner ? Vous serez éliminé de cette partie. Cette action est irréversible.",
252
"game.surrenderConfirmBtn": "Oui, abandonner",
253
"game.surrenderCancel": "Annuler",
254
"game.back": "Retour au menu",
255
"game.spectating": "Vous êtes éliminé. Vous pouvez encore regarder, envoyer des messages et, si le jury est actif, voter.",
256
"game.ceasefireLeft": "Temps restant de cessez-le-feu",
257
"game.ceasefireUntil": "Temps avant le cessez-le-feu",
258
"game.ceasefireActive": "Cessez-le-feu",
259
"game.attackDisabled": "Attaquer",
260
"game.attackDisabledReason": "Attaquer n'est pas autorisé pendant les heures de cessez-le-feu.",
261
"game.selectSelf": "Votre tank est sélectionné. Touchez une case mise en évidence pour vous déplacer, ou augmentez votre portée.",
262
"game.impassable": "Infranchissable",
263
"game.willShrink": "Cet anneau rétrécira ensuite",
264
"opt.info": "Infos",
265
"opt.attack": "Attaquer",
266
"opt.give": "Donner des points d'action",
267
"opt.message": "Envoyer un message",
268
"opt.close": "Fermer",
269
"info.title": "Infos",
270
"info.lives": "Vies",
271
"info.ap": "Points d'action",
272
"info.range": "Portée",
273
"info.notes": "Vos notes privées",
274
"info.notesHint": "Vous seul pouvez voir ces notes. Elles sont enregistrées avec votre compte.",
275
"info.saveNotes": "Enregistrer les notes",
276
"info.saved": "Enregistré",
277
"give.title": "Donner des points d'action",
278
"give.howMany": "Combien ?",
279
"give.send": "Donner",
280
"give.youHave": "Vous en avez {n}.",
281
"chat.title": "Message à {name}",
282
"chat.placeholder": "Écrire un message privé…",
283
"chat.send": "Envoyer",
284
"chat.empty": "Pas encore de messages.",
285
"jury.title": "Jury",
286
"jury.hint": "Votez pour un joueur vivant. Celui qui obtient le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution. Vous pouvez changer votre vote jusque-là. Les autres joueurs ne voient pas votre vote.",
287
"jury.vote": "Voter",
288
"jury.votedFor": "Vous avez voté pour {name}",
289
"jury.change": "Changer de vote",
290
"timeline.play": "Lecture",
291
"timeline.pause": "Pause",
292
"timeline.live": "En direct",
293
"timeline.event.start": "La partie commence",
294
"timeline.event.move": "{name} se déplace",
295
"timeline.event.shoot": "{name} tire sur {target}",
296
"timeline.event.give": "{name} donne {n} point(s) d'action à {target}",
297
"timeline.event.upgrade": "{name} porte sa portée à {n}",
298
"timeline.event.surrender": "{name} abandonne",
299
"timeline.event.daily": "Jour {n} : distribution des points d'action",
300
"timeline.event.jury": "Le jury attribue un bonus à {name}",
301
"timeline.event.juryTie": "Le jury attribue un bonus à {names}",
302
"timeline.event.shrink": "L'arène rétrécit",
303
"timeline.event.win": "{name} gagne",
304
"timeline.event.death": "{name} est éliminé",
305
"timeline.event.deathShot": "{name} est abattu par {by}",
306
"timeline.event.deathShrink": "{name} est pris par l'arène qui rétrécit",
307
"timeline.event.deathCrushed": "{name} est écrasé : plus aucune case libre",
308
"timeline.event.draw": "La partie se termine par un match nul",
309
"auth.unavailable": "La connexion est temporairement indisponible.",
310
"auth.backToGame": "Retour à Allianties",
311
"auth.failed": "Échec de la connexion.",
312
"auth.retry": "Réessayer",
313
"auth.back": "Retour",
314
"lang.choose": "Choisir la langue",
315
"lang.current": "Langue : {name}",
316
"error.login": "Connectez-vous pour continuer.",
317
"error.csrf": "Votre session a expiré. Actualisez la page et réessayez.",
318
"error.not_host": "Seul l'hôte peut faire cela.",
319
"error.min_players": "Il faut au moins deux joueurs pour commencer.",
320
"error.not_in_game": "Vous n'êtes pas dans cette partie.",
321
"error.dead": "Vous êtes éliminé de cette partie.",
322
"error.no_ap": "Vous n'avez plus de points d'action.",
323
"error.occupied": "Cette case est occupée.",
324
"error.impassable": "Cette case est infranchissable.",
325
"error.out_of_range": "Ce joueur est hors de portée.",
326
"error.invalid_move": "Ce coup n'est pas autorisé.",
327
"error.game_started": "Cette partie a déjà commencé.",
328
"error.game_finished": "Cette partie est terminée.",
329
"error.lobby_full": "Ce salon est complet.",
330
"error.unknown_code": "Aucun salon trouvé avec ce code.",
331
"error.cannot_vote": "Vous ne pouvez pas voter maintenant.",
332
"error.bad_vote": "Vous ne pouvez voter que pour un joueur vivant.",
333
"error.bad_give": "Vous ne pouvez pas donner autant de points d'action.",
334
"error.unknown_action": "Action inconnue.",
335
"error.ceasefire": "Vous ne pouvez pas attaquer pendant le cessez-le-feu.",
336
"error.generic": "Un problème est survenu. Veuillez réessayer.",
337
"error.serverStatus": "Le serveur a renvoyé {status}.",
338
}
339
340
ES = {
341
"app.name": NAME,
342
"menu.tagline": "Un juego de paciencia, alianzas y disparos bien calculados.",
343
"menu.login": "Iniciar sesión",
344
"menu.logout": "Cerrar sesión",
345
"menu.loggedInAs": "Sesión iniciada como",
346
"menu.localTest": "prueba local:",
347
"menu.create": "Nueva sala",
348
"menu.join": "Unirse",
349
"menu.codePlaceholder": "Código",
350
"menu.myGames": "Tus partidas",
351
"menu.noGames": "Aún no tienes partidas. Crea una sala e invita a otros.",
352
"menu.authUnconfiguredHtml": "El inicio de sesión aún no está configurado en este servidor. Hay que registrar la callback <code>/allianties/callback.php</code> en auth.timfalken.com y configurar el secreto del cliente.",
353
"menu.guestHint": "Inicia sesión para crear una sala, invitar jugadores y empezar una partida duradera.",
354
"menu.open": "Abrir",
355
"menu.continue": "Continuar",
356
"menu.statusLobby": "Sala",
357
"menu.statusRunning": "En juego",
358
"menu.statusFinished": "Terminada",
359
"menu.youWon": "Has ganado",
360
"menu.draw": "Empate",
361
"menu.winnerIs": "Ganador: {name}",
362
"menu.needLogin": "Inicia sesión primero para jugar.",
363
"menu.players": "Jugadores",
364
"lobby.title": "Sala",
365
"lobby.invite": "Invitar",
366
"lobby.copy": "Copiar enlace",
367
"lobby.copied": "Copiado",
368
"lobby.shareHint": "Comparte este código o enlace. Los jugadores inician sesión y se unen.",
369
"lobby.players": "Jugadores",
370
"lobby.start": "Empezar partida",
371
"lobby.leave": "Salir de la sala",
372
"lobby.host": "Anfitrión",
373
"lobby.you": "tú",
374
"lobby.minPlayers": "Hacen falta al menos dos jugadores para empezar.",
375
"lobby.needTwo": "Esperando al menos a un jugador más…",
376
"lobby.rules": "Reglas",
377
"lobby.jury": "Jurado",
378
"lobby.juryHint": "Los jugadores eliminados votan cada día por un jugador vivo. Quien recibe más votos obtiene un punto de acción extra en el siguiente reparto diario. En caso de empate, cada jugador empatado recibe la bonificación. Los votos son secretos y se pueden cambiar hasta entonces.",
379
"lobby.shrink": "Arena que se encoge",
380
"lobby.shrinkHint": "Tras un número configurable de días, el anillo exterior se vuelve intransitable en el reparto diario. Los jugadores que estén encima pierden una vida y son empujados hacia dentro.",
381
"lobby.shrinkDays": "Días entre encogimientos",
382
"lobby.shrinkDaysHint": "El primer encogimiento tras tantas medianoches, y luego cada vez que pasen otros tantos días, hasta el tamaño mínimo de la arena.",
383
"lobby.ceasefire": "Horas de alto el fuego forzoso",
384
"lobby.ceasefireHint": "Durante estas horas (Europe/Amsterdam) nadie puede disparar. Moverse, dar puntos de acción y mejorar el alcance siguen permitidos. Los periodos pueden cruzar la medianoche.",
385
"lobby.ceasefireAdd": "Añadir periodo",
386
"lobby.ceasefireRemove": "Quitar",
387
"lobby.ceasefireStart": "Desde",
388
"lobby.ceasefireEnd": "Hasta",
389
"lobby.ceasefireEmpty": "Aún no hay periodos. Añade uno o arrastra un sector en el reloj.",
390
"lobby.ceasefireClock": "Reloj de 24 horas. Arrastra los tiradores o pinta un sector; el rojo es alto el fuego, el oro es fuego libre. Horarios en Europe/Amsterdam.",
391
"lobby.waiting": "Esperando a que el anfitrión empiece la partida.",
392
"lobby.back": "Volver",
393
"lobby.code": "Código",
394
"lobby.playerCount.one": "{n} jugador",
395
"lobby.playerCount.other": "{n} jugadores",
396
"lobby.playerCount.few": "{n} jugadores",
397
"lobby.playerCount.many": "{n} jugadores",
398
"game.day": "Día {n}",
399
"game.nextAp": "Próximos puntos de acción",
400
"game.lives": "Vidas",
401
"game.ap": "Puntos de acción",
402
"game.range": "Alcance",
403
"game.you": "Tú",
404
"game.dead": "Eliminado",
405
"game.surrendered": "Se rindió",
406
"game.winner": "¡{name} gana!",
407
"game.youWin": "¡Has ganado!",
408
"game.draw": "La partida termina en empate.",
409
"game.shrinkIn": "La arena se encoge en {n} días",
410
"game.shrinkInDays.one": "La arena se encoge en {n} día",
411
"game.shrinkInDays.other": "La arena se encoge en {n} días",
412
"game.shrinkInDays.few": "La arena se encoge en {n} días",
413
"game.shrinkInDays.many": "La arena se encoge en {n} días",
414
"game.shrinkTomorrow": "La arena se encoge mañana",
415
"game.shrinkToday": "La arena se encoge en el siguiente reparto",
416
"game.upgrade": "Aumentar alcance",
417
"game.settings": "Ajustes",
418
"game.surrender": "Rendirse",
419
"game.surrenderConfirm": "¿Rendirse? Quedarás fuera de esta partida. No se puede deshacer.",
420
"game.surrenderConfirmBtn": "Sí, rendirme",
421
"game.surrenderCancel": "Cancelar",
422
"game.back": "Volver al menú",
423
"game.spectating": "Estás eliminado. Aún puedes observar, enviar mensajes y, si el jurado está activo, votar.",
424
"game.ceasefireLeft": "Tiempo restante de alto el fuego",
425
"game.ceasefireUntil": "Tiempo hasta el alto el fuego",
426
"game.ceasefireActive": "Alto el fuego",
427
"game.attackDisabled": "Atacar",
428
"game.attackDisabledReason": "No se puede atacar durante las horas de alto el fuego.",
429
"game.selectSelf": "Tu tanque está seleccionado. Toca una casilla destacada para moverte, o aumenta tu alcance.",
430
"game.impassable": "Intransitable",
431
"game.willShrink": "Este anillo se encogerá a continuación",
432
"opt.info": "Info",
433
"opt.attack": "Atacar",
434
"opt.give": "Dar puntos de acción",
435
"opt.message": "Enviar mensaje",
436
"opt.close": "Cerrar",
437
"info.title": "Info",
438
"info.lives": "Vidas",
439
"info.ap": "Puntos de acción",
440
"info.range": "Alcance",
441
"info.notes": "Tus notas privadas",
442
"info.notesHint": "Solo tú puedes ver estas notas. Se guardan con tu cuenta.",
443
"info.saveNotes": "Guardar notas",
444
"info.saved": "Guardado",
445
"give.title": "Dar puntos de acción",
446
"give.howMany": "¿Cuántos?",
447
"give.send": "Dar",
448
"give.youHave": "Tienes {n}.",
449
"chat.title": "Mensaje a {name}",
450
"chat.placeholder": "Escribe un mensaje privado…",
451
"chat.send": "Enviar",
452
"chat.empty": "Aún no hay mensajes.",
453
"jury.title": "Jurado",
454
"jury.hint": "Vota por un jugador vivo. Quien reciba más votos obtiene un punto de acción extra en el siguiente reparto. Puedes cambiar tu voto hasta entonces. Los demás no ven tu voto.",
455
"jury.vote": "Votar",
456
"jury.votedFor": "Has votado por {name}",
457
"jury.change": "Cambiar voto",
458
"timeline.play": "Reproducir",
459
"timeline.pause": "Pausa",
460
"timeline.live": "En directo",
461
"timeline.event.start": "Empieza la partida",
462
"timeline.event.move": "{name} se mueve",
463
"timeline.event.shoot": "{name} dispara a {target}",
464
"timeline.event.give": "{name} da {n} punto(s) de acción a {target}",
465
"timeline.event.upgrade": "{name} aumenta el alcance a {n}",
466
"timeline.event.surrender": "{name} se rinde",
467
"timeline.event.daily": "Día {n}: se reparten los puntos de acción",
468
"timeline.event.jury": "El jurado otorga una bonificación a {name}",
469
"timeline.event.juryTie": "El jurado otorga una bonificación a {names}",
470
"timeline.event.shrink": "La arena se encoge",
471
"timeline.event.win": "{name} gana",
472
"timeline.event.death": "{name} queda eliminado",
473
"timeline.event.deathShot": "{by} dispara a {name} y lo elimina",
474
"timeline.event.deathShrink": "{name} es alcanzado por la arena que se encoge",
475
"timeline.event.deathCrushed": "{name} queda aplastado: no queda ninguna casilla libre",
476
"timeline.event.draw": "La partida termina en empate",
477
"auth.unavailable": "El inicio de sesión no está disponible temporalmente.",
478
"auth.backToGame": "Volver a Allianties",
479
"auth.failed": "Error al iniciar sesión.",
480
"auth.retry": "Reintentar",
481
"auth.back": "Volver",
482
"lang.choose": "Elegir idioma",
483
"lang.current": "Idioma: {name}",
484
"error.login": "Inicia sesión para continuar.",
485
"error.csrf": "Tu sesión ha caducado. Actualiza la página e inténtalo de nuevo.",
486
"error.not_host": "Solo el anfitrión puede hacer eso.",
487
"error.min_players": "Hacen falta al menos dos jugadores para empezar.",
488
"error.not_in_game": "No estás en esta partida.",
489
"error.dead": "Has quedado eliminado de esta partida.",
490
"error.no_ap": "No te quedan puntos de acción.",
491
"error.occupied": "Esa casilla está ocupada.",
492
"error.impassable": "Esa casilla es intransitable.",
493
"error.out_of_range": "Ese jugador está fuera de alcance.",
494
"error.invalid_move": "Ese movimiento no está permitido.",
495
"error.game_started": "Esta partida ya ha empezado.",
496
"error.game_finished": "Esta partida ha terminado.",
497
"error.lobby_full": "Esta sala está llena.",
498
"error.unknown_code": "No se encontró ninguna sala con ese código.",
499
"error.cannot_vote": "Ahora no puedes votar.",
500
"error.bad_vote": "Solo puedes votar por un jugador vivo.",
501
"error.bad_give": "No puedes dar tantos puntos de acción.",
502
"error.unknown_action": "Acción desconocida.",
503
"error.ceasefire": "No puedes atacar durante el alto el fuego.",
504
"error.generic": "Algo salió mal. Inténtalo de nuevo.",
505
"error.serverStatus": "El servidor devolvió {status}.",
506
}
507
508
PL = {
509
"app.name": NAME,
510
"menu.tagline": "Gra cierpliwości, sojuszy i dobrze wycelowanych strzałów.",
511
"menu.login": "Zaloguj się",
512
"menu.logout": "Wyloguj się",
513
"menu.loggedInAs": "Zalogowano jako",
514
"menu.localTest": "test lokalny:",
515
"menu.create": "Nowe lobby",
516
"menu.join": "Dołącz",
517
"menu.codePlaceholder": "Kod",
518
"menu.myGames": "Twoje gry",
519
"menu.noGames": "Nie masz jeszcze żadnych gier. Załóż lobby i zaproś innych.",
520
"menu.authUnconfiguredHtml": "Logowanie nie jest jeszcze skonfigurowane na tym serwerze. Callback <code>/allianties/callback.php</code> musi zostać zarejestrowany w auth.timfalken.com, a sekret klienta musi zostać ustawiony.",
521
"menu.guestHint": "Zaloguj się, aby utworzyć lobby, zaprosić graczy i rozpocząć trwałą rozgrywkę.",
522
"menu.open": "Otwórz",
523
"menu.continue": "Kontynuuj",
524
"menu.statusLobby": "Lobby",
525
"menu.statusRunning": "W toku",
526
"menu.statusFinished": "Zakończona",
527
"menu.youWon": "Wygrana",
528
"menu.draw": "Remis",
529
"menu.winnerIs": "Zwycięzca: {name}",
530
"menu.needLogin": "Najpierw zaloguj się, aby zagrać.",
531
"menu.players": "Gracze",
532
"lobby.title": "Lobby",
533
"lobby.invite": "Zaproś",
534
"lobby.copy": "Kopiuj link",
535
"lobby.copied": "Skopiowano",
536
"lobby.shareHint": "Udostępnij ten kod lub link. Gracze logują się i dołączają.",
537
"lobby.players": "Gracze",
538
"lobby.start": "Rozpocznij grę",
539
"lobby.leave": "Opuść lobby",
540
"lobby.host": "Gospodarz",
541
"lobby.you": "ty",
542
"lobby.minPlayers": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",
543
"lobby.needTwo": "Oczekiwanie na co najmniej jednego gracza…",
544
"lobby.rules": "Zasady",
545
"lobby.jury": "Jury",
546
"lobby.juryHint": "Eliminowani gracze codziennie głosują na żywego gracza. Osoba z największą liczbą głosów otrzymuje dodatkowy punkt akcji przy kolejnym codziennym rozdaniu. Przy remisie bonus dostaje każdy z ex aequo. Głosy są tajne i można je zmieniać do tego momentu.",
547
"lobby.shrink": "Kurcząca się arena",
548
"lobby.shrinkHint": "Po ustalonej liczbie dni zewnętrzny pierścień staje się nieprzekraczalny przy codziennym rozdaniu. Gracze, którzy na nim stoją, tracą jedno życie i są spychani do środka.",
549
"lobby.shrinkDays": "Dni między skurczeniami",
550
"lobby.shrinkDaysHint": "Pierwsze skurczenie po tylu północach, potem ponownie co tyle samo dni, aż arena osiągnie minimalny rozmiar.",
551
"lobby.ceasefire": "Wymuszone godziny zawieszenia broni",
552
"lobby.ceasefireHint": "W tych godzinach (Europe/Amsterdam) nikt nie może strzelać. Ruch, przekazywanie punktów akcji i zwiększanie zasięgu pozostają dozwolone. Zakresy mogą przekraczać północ.",
553
"lobby.ceasefireAdd": "Dodaj okres",
554
"lobby.ceasefireRemove": "Usuń",
555
"lobby.ceasefireStart": "Od",
556
"lobby.ceasefireEnd": "Do",
557
"lobby.ceasefireEmpty": "Brak okresów. Dodaj jeden albo narysuj wycinek na zegarze.",
558
"lobby.ceasefireClock": "Zegar 24-godzinny. Przeciągaj uchwyty lub maluj wycinek; czerwień to zawieszenie broni, złoto to dowolność strzału. Czas: Europe/Amsterdam.",
559
"lobby.waiting": "Czekamy, aż gospodarz rozpocznie grę.",
560
"lobby.back": "Wstecz",
561
"lobby.code": "Kod",
562
"lobby.playerCount.one": "{n} gracz",
563
"lobby.playerCount.other": "{n} graczy",
564
"lobby.playerCount.few": "{n} graczy",
565
"lobby.playerCount.many": "{n} graczy",
566
"game.day": "Dzień {n}",
567
"game.nextAp": "Następne punkty akcji",
568
"game.lives": "Życia",
569
"game.ap": "Punkty akcji",
570
"game.range": "Zasięg",
571
"game.you": "Ty",
572
"game.dead": "Eliminacja",
573
"game.surrendered": "Poddał się",
574
"game.winner": "{name} wygrywa!",
575
"game.youWin": "Wygrywasz!",
576
"game.draw": "Gra kończy się remisem.",
577
"game.shrinkIn": "Arena skurczy się za {n} dni",
578
"game.shrinkInDays.one": "Arena skurczy się za {n} dzień",
579
"game.shrinkInDays.other": "Arena skurczy się za {n} dni",
580
"game.shrinkInDays.few": "Arena skurczy się za {n} dni",
581
"game.shrinkInDays.many": "Arena skurczy się za {n} dni",
582
"game.shrinkTomorrow": "Arena skurczy się jutro",
583
"game.shrinkToday": "Arena skurczy się przy następnym rozdaniu",
584
"game.upgrade": "Zwiększ zasięg",
585
"game.settings": "Ustawienia",
586
"game.surrender": "Poddaj się",
587
"game.surrenderConfirm": "Poddać się? Odpadniesz z tej gry. Tej czynności nie można cofnąć.",
588
"game.surrenderConfirmBtn": "Tak, poddaję się",
589
"game.surrenderCancel": "Anuluj",
590
"game.back": "Powrót do menu",
591
"game.spectating": "Odpadłeś. Nadal możesz oglądać, wysyłać wiadomości i — jeśli jury jest włączone — głosować.",
592
"game.ceasefireLeft": "Pozostały czas zawieszenia broni",
593
"game.ceasefireUntil": "Czas do zawieszenia broni",
594
"game.ceasefireActive": "Zawieszenie broni",
595
"game.attackDisabled": "Atak",
596
"game.attackDisabledReason": "Atak jest niedozwolony w godzinach zawieszenia broni.",
597
"game.selectSelf": "Twój czołg jest zaznaczony. Dotknij podświetlonego pola, aby się ruszyć, albo zwiększ zasięg.",
598
"game.impassable": "Nieprzekraczalne",
599
"game.willShrink": "Ten pierścień skurczy się jako następny",
600
"opt.info": "Informacje",
601
"opt.attack": "Atakuj",
602
"opt.give": "Przekaż punkty akcji",
603
"opt.message": "Wyślij wiadomość",
604
"opt.close": "Zamknij",
605
"info.title": "Informacje",
606
"info.lives": "Życia",
607
"info.ap": "Punkty akcji",
608
"info.range": "Zasięg",
609
"info.notes": "Twoje prywatne notatki",
610
"info.notesHint": "Tylko ty widzisz te notatki. Są przechowywane przy twoim koncie.",
611
"info.saveNotes": "Zapisz notatki",
612
"info.saved": "Zapisano",
613
"give.title": "Przekaż punkty akcji",
614
"give.howMany": "Ile?",
615
"give.send": "Przekaż",
616
"give.youHave": "Masz {n}.",
617
"chat.title": "Wiadomość do {name}",
618
"chat.placeholder": "Napisz prywatną wiadomość…",
619
"chat.send": "Wyślij",
620
"chat.empty": "Nie ma jeszcze wiadomości.",
621
"jury.title": "Jury",
622
"jury.hint": "Zagłosuj na jednego żywego gracza. Osoba z największą liczbą głosów otrzyma dodatkowy punkt akcji przy następnym rozdaniu. Do tego czasu możesz zmienić głos. Inni gracze go nie widzą.",
623
"jury.vote": "Głosuj",
624
"jury.votedFor": "Zagłosowałeś na {name}",
625
"jury.change": "Zmień głos",
626
"timeline.play": "Odtwórz",
627
"timeline.pause": "Pauza",
628
"timeline.live": "Na żywo",
629
"timeline.event.start": "Gra się zaczyna",
630
"timeline.event.move": "{name} się przemieszcza",
631
"timeline.event.shoot": "{name} strzela do {target}",
632
"timeline.event.give": "{name} przekazuje {n} pkt. akcji dla {target}",
633
"timeline.event.upgrade": "{name} zwiększa zasięg do {n}",
634
"timeline.event.surrender": "{name} się poddaje",
635
"timeline.event.daily": "Dzień {n}: rozdanie punktów akcji",
636
"timeline.event.jury": "Jury przyznaje bonus dla {name}",
637
"timeline.event.juryTie": "Jury przyznaje bonus dla {names}",
638
"timeline.event.shrink": "Arena się kurczy",
639
"timeline.event.win": "{name} wygrywa",
640
"timeline.event.death": "{name} odpada",
641
"timeline.event.deathShot": "{name} zostaje zestrzelony przez {by}",
642
"timeline.event.deathShrink": "{name} zostaje złapany przez kurczącą się arenę",
643
"timeline.event.deathCrushed": "{name} zostaje zmiażdżony: nie ma wolnego pola",
644
"timeline.event.draw": "Gra kończy się remisem",
645
"auth.unavailable": "Logowanie jest chwilowo niedostępne.",
646
"auth.backToGame": "Powrót do Allianties",
647
"auth.failed": "Logowanie nie powiodło się.",
648
"auth.retry": "Spróbuj ponownie",
649
"auth.back": "Wstecz",
650
"lang.choose": "Wybierz język",
651
"lang.current": "Język: {name}",
652
"error.login": "Zaloguj się, aby kontynuować.",
653
"error.csrf": "Twoja sesja wygasła. Odśwież stronę i spróbuj ponownie.",
654
"error.not_host": "Tylko gospodarz może to zrobić.",
655
"error.min_players": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",
656
"error.not_in_game": "Nie jesteś w tej grze.",
657
"error.dead": "Odpadłeś z tej gry.",
658
"error.no_ap": "Nie masz już punktów akcji.",
659
"error.occupied": "To pole jest zajęte.",
660
"error.impassable": "To pole jest nieprzekraczalne.",
661
"error.out_of_range": "Ten gracz jest poza zasięgiem.",
662
"error.invalid_move": "Ten ruch jest niedozwolony.",
663
"error.game_started": "Ta gra już się rozpoczęła.",
664
"error.game_finished": "Ta gra się zakończyła.",
665
"error.lobby_full": "To lobby jest pełne.",
666
"error.unknown_code": "Nie znaleziono lobby o takim kodzie.",
667
"error.cannot_vote": "Teraz nie możesz głosować.",
668
"error.bad_vote": "Możesz głosować tylko na żywego gracza.",
669
"error.bad_give": "Nie możesz przekazać tylu punktów akcji.",
670
"error.unknown_action": "Nieznana akcja.",
671
"error.ceasefire": "Nie możesz atakować w godzinach zawieszenia broni.",
672
"error.generic": "Coś poszło nie tak. Spróbuj ponownie.",
673
"error.serverStatus": "Serwer zwrócił {status}.",
674
}
675
676
RU = {
677
"app.name": NAME,
678
"menu.tagline": "Игра в терпение, союзы и точно timed выстрелы.".replace("точно timed", "хорошо рассчитанные"),
679
"menu.login": "Войти",
680
"menu.logout": "Выйти",
681
"menu.loggedInAs": "Вы вошли как",
682
"menu.localTest": "локальный тест:",
683
"menu.create": "Новое лобби",
684
"menu.join": "Присоединиться",
685
"menu.codePlaceholder": "Код",
686
"menu.myGames": "Ваши игры",
687
"menu.noGames": "У вас пока нет игр. Создайте лобби и пригласите других.",
688
"menu.authUnconfiguredHtml": "Вход на этом сервере ещё не настроен. Callback <code>/allianties/callback.php</code> нужно зарегистрировать на auth.timfalken.com, а секрет клиента — задать.",
689
"menu.guestHint": "Войдите, чтобы создать лобби, пригласить игроков и начать долгую партию.",
690
"menu.open": "Открыть",
691
"menu.continue": "Продолжить",
692
"menu.statusLobby": "Лобби",
693
"menu.statusRunning": "Идёт игра",
694
"menu.statusFinished": "Завершена",
695
"menu.youWon": "Вы победили",
696
"menu.draw": "Ничья",
697
"menu.winnerIs": "Победитель: {name}",
698
"menu.needLogin": "Сначала войдите, чтобы играть.",
699
"menu.players": "Игроки",
700
"lobby.title": "Лобби",
701
"lobby.invite": "Пригласить",
702
"lobby.copy": "Копировать ссылку",
703
"lobby.copied": "Скопировано",
704
"lobby.shareHint": "Поделитесь этим кодом или ссылкой. Игроки входят в аккаунт и присоединяются.",
705
"lobby.players": "Игроки",
706
"lobby.start": "Начать игру",
707
"lobby.leave": "Покинуть лобби",
708
"lobby.host": "Хозяин",
709
"lobby.you": "вы",
710
"lobby.minPlayers": "Для начала нужно как минимум два игрока.",
711
"lobby.needTwo": "Ждём ещё хотя бы одного игрока…",
712
"lobby.rules": "Правила",
713
"lobby.jury": "Жюри",
714
"lobby.juryHint": "Выбывшие игроки каждый день голосуют за живого игрока. Набравший больше всех голосов получает дополнительное очко действия при следующем ежедневном начислении. При ничьей бонус получают все, кто набрал одинаково максимум. Голоса тайные и их можно менять до начисления.",
715
"lobby.shrink": "Сжимающаяся арена",
716
"lobby.shrinkHint": "Через заданное число дней внешнее кольцо становится непроходимым в момент ежедневного начисления. Игроки, стоящие на нём, теряют одну жизнь и сдвигаются внутрь.",
717
"lobby.shrinkDays": "Дней между сжатиями",
718
"lobby.shrinkDaysHint": "Первое сжатие после стольких полуночей, затем снова через столько же дней, пока арена не достигнет минимального размера.",
719
"lobby.ceasefire": "Принудительное перемирие",
720
"lobby.ceasefireHint": "В эти часы (Europe/Amsterdam) стрелять нельзя. Ходить, передавать очки действия и увеличивать дальность по-прежнему можно. Интервалы могут переходить через полночь.",
721
"lobby.ceasefireAdd": "Добавить период",
722
"lobby.ceasefireRemove": "Удалить",
723
"lobby.ceasefireStart": "С",
724
"lobby.ceasefireEnd": "До",
725
"lobby.ceasefireEmpty": "Периодов пока нет. Добавьте один или нарисуйте сектор на часах.",
726
"lobby.ceasefireClock": "24-часовые часы. Перетаскивайте ручки или рисуйте сектор; красный — перемирие, золотой — огонь разрешён. Время: Europe/Amsterdam.",
727
"lobby.waiting": "Ждём, пока хозяин начнёт игру.",
728
"lobby.back": "Назад",
729
"lobby.code": "Код",
730
"lobby.playerCount.one": "{n} игрок",
731
"lobby.playerCount.other": "{n} игроков",
732
"lobby.playerCount.few": "{n} игрока",
733
"lobby.playerCount.many": "{n} игроков",
734
"game.day": "День {n}",
735
"game.nextAp": "Следующие очки действия",
736
"game.lives": "Жизни",
737
"game.ap": "Очки действия",
738
"game.range": "Дальность",
739
"game.you": "Вы",
740
"game.dead": "Выбыл",
741
"game.surrendered": "Сдался",
742
"game.winner": "{name} побеждает!",
743
"game.youWin": "Вы победили!",
744
"game.draw": "Игра заканчивается вничью.",
745
"game.shrinkIn": "Арена сожмётся через {n} дн.",
746
"game.shrinkInDays.one": "Арена сожмётся через {n} день",
747
"game.shrinkInDays.other": "Арена сожмётся через {n} дней",
748
"game.shrinkInDays.few": "Арена сожмётся через {n} дня",
749
"game.shrinkInDays.many": "Арена сожмётся через {n} дней",
750
"game.shrinkTomorrow": "Арена сожмётся завтра",
751
"game.shrinkToday": "Арена сожмётся при следующем начислении",
752
"game.upgrade": "Увеличить дальность",
753
"game.settings": "Настройки",
754
"game.surrender": "Сдаться",
755
"game.surrenderConfirm": "Сдаться? Вы выбудете из этой игры. Это нельзя отменить.",
756
"game.surrenderConfirmBtn": "Да, сдаться",
757
"game.surrenderCancel": "Отмена",
758
"game.back": "Вернуться в меню",
759
"game.spectating": "Вы выбыли. Можно смотреть, писать сообщения и, если жюри включено, голосовать.",
760
"game.ceasefireLeft": "До конца перемирия",
761
"game.ceasefireUntil": "До начала перемирия",
762
"game.ceasefireActive": "Перемирие",
763
"game.attackDisabled": "Атака",
764
"game.attackDisabledReason": "Во время перемирия атаковать нельзя.",
765
"game.selectSelf": "Ваш танк выбран. Нажмите подсвеченную клетку, чтобы пойти, или увеличьте дальность.",
766
"game.impassable": "Непроходимо",
767
"game.willShrink": "Это кольцо сожмётся следующим",
768
"opt.info": "Сведения",
769
"opt.attack": "Атаковать",
770
"opt.give": "Отдать очки действия",
771
"opt.message": "Отправить сообщение",
772
"opt.close": "Закрыть",
773
"info.title": "Сведения",
774
"info.lives": "Жизни",
775
"info.ap": "Очки действия",
776
"info.range": "Дальность",
777
"info.notes": "Ваши личные заметки",
778
"info.notesHint": "Эти заметки видите только вы. Они хранятся в вашем аккаунте.",
779
"info.saveNotes": "Сохранить заметки",
780
"info.saved": "Сохранено",
781
"give.title": "Отдать очки действия",
782
"give.howMany": "Сколько?",
783
"give.send": "Отдать",
784
"give.youHave": "У вас {n}.",
785
"chat.title": "Сообщение для {name}",
786
"chat.placeholder": "Напишите личное сообщение…",
787
"chat.send": "Отправить",
788
"chat.empty": "Сообщений пока нет.",
789
"jury.title": "Жюри",
790
"jury.hint": "Голосуйте за одного живого игрока. Набравший больше всех голосов получит дополнительное очко действия при следующем начислении. Голос можно менять до этого момента. Другие игроки его не видят.",
791
"jury.vote": "Голосовать",
792
"jury.votedFor": "Вы проголосовали за {name}",
793
"jury.change": "Изменить голос",
794
"timeline.play": "Воспроизвести",
795
"timeline.pause": "Пауза",
796
"timeline.live": "Сейчас",
797
"timeline.event.start": "Игра начинается",
798
"timeline.event.move": "{name} перемещается",
799
"timeline.event.shoot": "{name} стреляет в {target}",
800
"timeline.event.give": "{name} отдаёт {n} очк. действия игроку {target}",
801
"timeline.event.upgrade": "{name} увеличивает дальность до {n}",
802
"timeline.event.surrender": "{name} сдаётся",
803
"timeline.event.daily": "День {n}: начисление очков действия",
804
"timeline.event.jury": "Жюри присуждает бонус игроку {name}",
805
"timeline.event.juryTie": "Жюри присуждает бонус игрокам {names}",
806
"timeline.event.shrink": "Арена сжимается",
807
"timeline.event.win": "{name} побеждает",
808
"timeline.event.death": "{name} выбывает",
809
"timeline.event.deathShot": "{name} подбит игроком {by}",
810
"timeline.event.deathShrink": "{name} задевает сжимающаяся арена",
811
"timeline.event.deathCrushed": "{name} раздавлен: свободных клеток не осталось",
812
"timeline.event.draw": "Игра заканчивается вничью",
813
"auth.unavailable": "Вход временно недоступен.",
814
"auth.backToGame": "Назад в Allianties",
815
"auth.failed": "Не удалось войти.",
816
"auth.retry": "Попробовать снова",
817
"auth.back": "Назад",
818
"lang.choose": "Выберите язык",
819
"lang.current": "Язык: {name}",
820
"error.login": "Войдите, чтобы продолжить.",
821
"error.csrf": "Сессия истекла. Обновите страницу и попробуйте снова.",
822
"error.not_host": "Это может сделать только хозяин.",
823
"error.min_players": "Для начала нужно как минимум два игрока.",
824
"error.not_in_game": "Вас нет в этой игре.",
825
"error.dead": "Вы выбыли из этой игры.",
826
"error.no_ap": "У вас не осталось очков действия.",
827
"error.occupied": "Эта клетка занята.",
828
"error.impassable": "Эта клетка непроходима.",
829
"error.out_of_range": "Этот игрок вне досягаемости.",
830
"error.invalid_move": "Этот ход недопустим.",
831
"error.game_started": "Эта игра уже началась.",
832
"error.game_finished": "Эта игра уже закончена.",
833
"error.lobby_full": "Это лобби заполнено.",
834
"error.unknown_code": "Лобби с таким кодом не найдено.",
835
"error.cannot_vote": "Сейчас вы не можете голосовать.",
836
"error.bad_vote": "Голосовать можно только за живого игрока.",
837
"error.bad_give": "Столько очков действия отдать нельзя.",
838
"error.unknown_action": "Неизвестное действие.",
839
"error.ceasefire": "Во время перемирия атаковать нельзя.",
840
"error.generic": "Что-то пошло не так. Попробуйте ещё раз.",
841
"error.serverStatus": "Сервер вернул {status}.",
842
}
843
844
JA = {
845
"app.name": NAME,
846
"menu.tagline": "忍耐、同盟、そして時機を逃さない一撃のゲーム。",
847
"menu.login": "ログイン",
848
"menu.logout": "ログアウト",
849
"menu.loggedInAs": "ログイン中",
850
"menu.localTest": "ローカルテスト:",
851
"menu.create": "新しいロビー",
852
"menu.join": "参加",
853
"menu.codePlaceholder": "コード",
854
"menu.myGames": "あなたのゲーム",
855
"menu.noGames": "まだゲームがありません。ロビーを作って他の人を招待しましょう。",
856
"menu.authUnconfiguredHtml": "このサーバーではまだログインが設定されていません。コールバック <code>/allianties/callback.php</code> を auth.timfalken.com に登録し、クライアントシークレットを設定する必要があります。",
857
"menu.guestHint": "ログインすると、ロビーの作成、招待、長く続くゲームの開始ができます。",
858
"menu.open": "開く",
859
"menu.continue": "続ける",
860
"menu.statusLobby": "ロビー",
861
"menu.statusRunning": "プレイ中",
862
"menu.statusFinished": "終了",
863
"menu.youWon": "勝利",
864
"menu.draw": "引き分け",
865
"menu.winnerIs": "勝者:{name}",
866
"menu.needLogin": "プレイするには、まずログインしてください。",
867
"menu.players": "プレイヤー",
868
"lobby.title": "ロビー",
869
"lobby.invite": "招待",
870
"lobby.copy": "リンクをコピー",
871
"lobby.copied": "コピーしました",
872
"lobby.shareHint": "このコードまたはリンクを共有してください。プレイヤーはログインして参加します。",
873
"lobby.players": "プレイヤー",
874
"lobby.start": "ゲームを開始",
875
"lobby.leave": "ロビーを退出",
876
"lobby.host": "ホスト",
877
"lobby.you": "あなた",
878
"lobby.minPlayers": "開始するには少なくとも2人必要です。",
879
"lobby.needTwo": "あと少なくとも1人を待っています…",
880
"lobby.rules": "ルール",
881
"lobby.jury": "陪審",
882
"lobby.juryHint": "脱落したプレイヤーは毎日、生存中のプレイヤー1人に投票します。最多得票のプレイヤーは、次の毎日配布で行動力を1つ余分に受け取ります。同票の場合は、同票の全員がボーナスを受け取ります。投票は秘密で、配布まで変更できます。",
883
"lobby.shrink": "縮小する戦場",
884
"lobby.shrinkHint": "設定した日数ごとに、毎日の配布のときに外周が通行不能になります。その上にいるプレイヤーはライフを1失い、内側へ押し出されます。",
885
"lobby.shrinkDays": "縮小の間隔(日)",
886
"lobby.shrinkDaysHint": "最初の縮小はこの回数の深夜のあと、その後同じ日数ごとに繰り返し、戦場が最小サイズになるまで続きます。",
887
"lobby.ceasefire": "強制停戦時間",
888
"lobby.ceasefireHint": "この時間帯(Europe/Amsterdam)は誰も撃てません。移動、行動力の譲渡、射程の強化は可能です。時間帯は深夜をまたげます。",
889
"lobby.ceasefireAdd": "時間帯を追加",
890
"lobby.ceasefireRemove": "削除",
891
"lobby.ceasefireStart": "開始",
892
"lobby.ceasefireEnd": "終了",
893
"lobby.ceasefireEmpty": "まだ時間帯がありません。追加するか、時計の上で扇形をドラッグしてください。",
894
"lobby.ceasefireClock": "24時間時計。ハンドルをドラッグするか扇形を描きます。赤は停戦、金は攻撃可能。時刻は Europe/Amsterdam です。",
895
"lobby.waiting": "ホストがゲームを開始するのを待っています。",
896
"lobby.back": "戻る",
897
"lobby.code": "コード",
898
"lobby.playerCount.one": "{n}人のプレイヤー",
899
"lobby.playerCount.other": "{n}人のプレイヤー",
900
"lobby.playerCount.few": "{n}人のプレイヤー",
901
"lobby.playerCount.many": "{n}人のプレイヤー",
902
"game.day": "{n}日目",
903
"game.nextAp": "次の行動力",
904
"game.lives": "ライフ",
905
"game.ap": "行動力",
906
"game.range": "射程",
907
"game.you": "あなた",
908
"game.dead": "脱落",
909
"game.surrendered": "降伏",
910
"game.winner": "{name}の勝利!",
911
"game.youWin": "あなたの勝利!",
912
"game.draw": "引き分けでゲーム終了です。",
913
"game.shrinkIn": "戦場は{n}日後に縮小します",
914
"game.shrinkInDays.one": "戦場は{n}日後に縮小します",
915
"game.shrinkInDays.other": "戦場は{n}日後に縮小します",
916
"game.shrinkInDays.few": "戦場は{n}日後に縮小します",
917
"game.shrinkInDays.many": "戦場は{n}日後に縮小します",
918
"game.shrinkTomorrow": "戦場は明日縮小します",
919
"game.shrinkToday": "戦場は次の配布時に縮小します",
920
"game.upgrade": "射程を伸ばす",
921
"game.settings": "設定",
922
"game.surrender": "降伏する",
923
"game.surrenderConfirm": "降伏しますか?このゲームから脱落します。取り消すことはできません。",
924
"game.surrenderConfirmBtn": "はい、降伏する",
925
"game.surrenderCancel": "キャンセル",
926
"game.back": "メニューに戻る",
927
"game.spectating": "あなたは脱落しました。観戦、メッセージ送信、陪審がオンなら投票はできます。",
928
"game.ceasefireLeft": "停戦の残り時間",
929
"game.ceasefireUntil": "停戦までの時間",
930
"game.ceasefireActive": "停戦中",
931
"game.attackDisabled": "攻撃",
932
"game.attackDisabledReason": "停戦時間中は攻撃できません。",
933
"game.selectSelf": "自分の戦車が選ばれています。ハイライトされたマスをタップして移動するか、射程を伸ばしてください。",
934
"game.impassable": "通行不能",
935
"game.willShrink": "次に縮小する輪",
936
"opt.info": "情報",
937
"opt.attack": "攻撃",
938
"opt.give": "行動力を渡す",
939
"opt.message": "メッセージを送る",
940
"opt.close": "閉じる",
941
"info.title": "情報",
942
"info.lives": "ライフ",
943
"info.ap": "行動力",
944
"info.range": "射程",
945
"info.notes": "非公開のメモ",
946
"info.notesHint": "このメモはあなただけが見られます。アカウントに保存されます。",
947
"info.saveNotes": "メモを保存",
948
"info.saved": "保存しました",
949
"give.title": "行動力を渡す",
950
"give.howMany": "いくつ?",
951
"give.send": "渡す",
952
"give.youHave": "あなたは{n}持っています。",
953
"chat.title": "{name}へのメッセージ",
954
"chat.placeholder": "非公開メッセージを書く…",
955
"chat.send": "送信",
956
"chat.empty": "まだメッセージはありません。",
957
"jury.title": "陪審",
958
"jury.hint": "生存中のプレイヤー1人に投票します。最多得票者は次の配布で行動力を1つ余分に得ます。それまで投票は変更できます。他のプレイヤーに投票は見えません。",
959
"jury.vote": "投票する",
960
"jury.votedFor": "{name}に投票しました",
961
"jury.change": "投票を変更",
962
"timeline.play": "再生",
963
"timeline.pause": "一時停止",
964
"timeline.live": "ライブ",
965
"timeline.event.start": "ゲーム開始",
966
"timeline.event.move": "{name}が移動",
967
"timeline.event.shoot": "{name}が{target}を撃つ",
968
"timeline.event.give": "{name}が{target}に行動力を{n}渡す",
969
"timeline.event.upgrade": "{name}が射程を{n}に伸ばす",
970
"timeline.event.surrender": "{name}が降伏",
971
"timeline.event.daily": "{n}日目:行動力の配布",
972
"timeline.event.jury": "陪審が{name}にボーナスを与える",
973
"timeline.event.juryTie": "陪審が{names}にボーナスを与える",
974
"timeline.event.shrink": "戦場が縮小する",
975
"timeline.event.win": "{name}の勝利",
976
"timeline.event.death": "{name}が脱落",
977
"timeline.event.deathShot": "{name}が{by}に撃たれて脱落",
978
"timeline.event.deathShrink": "{name}が縮小する戦場に巻き込まれた",
979
"timeline.event.deathCrushed": "{name}は押しつぶされた:空きマスがない",
980
"timeline.event.draw": "引き分けで終了",
981
"auth.unavailable": "ログインは一時的に利用できません。",
982
"auth.backToGame": "Alliantiesに戻る",
983
"auth.failed": "ログインに失敗しました。",
984
"auth.retry": "再試行",
985
"auth.back": "戻る",
986
"lang.choose": "言語を選択",
987
"lang.current": "言語:{name}",
988
"error.login": "続けるにはログインしてください。",
989
"error.csrf": "セッションの期限が切れました。ページを更新してもう一度お試しください。",
990
"error.not_host": "ホストだけがそれを行えます。",
991
"error.min_players": "開始するには少なくとも2人必要です。",
992
"error.not_in_game": "このゲームには参加していません。",
993
"error.dead": "このゲームから脱落しています。",
994
"error.no_ap": "行動力が残っていません。",
995
"error.occupied": "そのマスは占有されています。",
996
"error.impassable": "そのマスは通行不能です。",
997
"error.out_of_range": "そのプレイヤーは射程外です。",
998
"error.invalid_move": "その行動はできません。",
999
"error.game_started": "このゲームはすでに始まっています。",
1000
"error.game_finished": "このゲームは終了しています。",
1001
"error.lobby_full": "このロビーは満員です。",
1002
"error.unknown_code": "そのコードのロビーは見つかりません。",
1003
"error.cannot_vote": "今は投票できません。",
1004
"error.bad_vote": "生存中のプレイヤーにしか投票できません。",
1005
"error.bad_give": "そんなに多くの行動力は渡せません。",
1006
"error.unknown_action": "不明な行動です。",
1007
"error.ceasefire": "停戦時間中は攻撃できません。",
1008
"error.generic": "問題が発生しました。もう一度お試しください。",
1009
"error.serverStatus": "サーバーは{status}を返しました。",
1010
}
1011
1012
ZH = {
1013
"app.name": NAME,
1014
"menu.tagline": "一场关于耐心、同盟与精准开火的游戏。",
1015
"menu.login": "登录",
1016
"menu.logout": "退出登录",
1017
"menu.loggedInAs": "已登录为",
1018
"menu.localTest": "本地测试:",
1019
"menu.create": "新建大厅",
1020
"menu.join": "加入",
1021
"menu.codePlaceholder": "代码",
1022
"menu.myGames": "你的对局",
1023
"menu.noGames": "你还没有任何对局。新建一个大厅并邀请其他人吧。",
1024
"menu.authUnconfiguredHtml": "此服务器尚未设置登录。需要在 auth.timfalken.com 上注册回调 <code>/allianties/callback.php</code>,并配置客户端密钥。",
1025
"menu.guestHint": "登录后可以创建大厅、邀请玩家并开始一局长时间进行的游戏。",
1026
"menu.open": "打开",
1027
"menu.continue": "继续",
1028
"menu.statusLobby": "大厅",
1029
"menu.statusRunning": "进行中",
1030
"menu.statusFinished": "已结束",
1031
"menu.youWon": "你赢了",
1032
"menu.draw": "平局",
1033
"menu.winnerIs": "胜者:{name}",
1034
"menu.needLogin": "请先登录再游戏。",
1035
"menu.players": "玩家",
1036
"lobby.title": "大厅",
1037
"lobby.invite": "邀请",
1038
"lobby.copy": "复制链接",
1039
"lobby.copied": "已复制",
1040
"lobby.shareHint": "分享此代码或链接。玩家登录后即可加入。",
1041
"lobby.players": "玩家",
1042
"lobby.start": "开始游戏",
1043
"lobby.leave": "离开大厅",
1044
"lobby.host": "房主",
1045
"lobby.you": "你",
1046
"lobby.minPlayers": "至少需要两名玩家才能开始。",
1047
"lobby.needTwo": "正在等待至少再来一名玩家…",
1048
"lobby.rules": "规则",
1049
"lobby.jury": "陪审团",
1050
"lobby.juryHint": "被淘汰的玩家每天为一名仍存活的玩家投票。得票最多的玩家在下一次每日发放时额外获得 1 点行动点。若并列,所有并列者都获得奖励。投票对他人保密,并可在发放前更改。",
1051
"lobby.shrink": "缩小的战场",
1052
"lobby.shrinkHint": "每隔设定的天数,在每日发放时外圈会变为不可通行。站在上面的玩家失去 1 点生命并被推向内侧。",
1053
"lobby.shrinkDays": "两次缩小间隔天数",
1054
"lobby.shrinkDaysHint": "第一次缩小发生在这么多个午夜之后,之后每隔同样天数再缩小,直到战场达到最小尺寸。",
1055
"lobby.ceasefire": "强制停火时段",
1056
"lobby.ceasefireHint": "在这些时段(Europe/Amsterdam)任何人不得射击。移动、给予行动点和提升射程仍然允许。时段可以跨越午夜。",
1057
"lobby.ceasefireAdd": "添加时段",
1058
"lobby.ceasefireRemove": "删除",
1059
"lobby.ceasefireStart": "从",
1060
"lobby.ceasefireEnd": "至",
1061
"lobby.ceasefireEmpty": "还没有时段。请添加一个,或在时钟上拖出一段扇形。",
1062
"lobby.ceasefireClock": "24 小时时钟。拖动手柄或画出扇形;红色为停火,金色为可开火。时间为 Europe/Amsterdam。",
1063
"lobby.waiting": "等待房主开始游戏。",
1064
"lobby.back": "返回",
1065
"lobby.code": "代码",
1066
"lobby.playerCount.one": "{n} 名玩家",
1067
"lobby.playerCount.other": "{n} 名玩家",
1068
"lobby.playerCount.few": "{n} 名玩家",
1069
"lobby.playerCount.many": "{n} 名玩家",
1070
"game.day": "第 {n} 天",
1071
"game.nextAp": "下次行动点",
1072
"game.lives": "生命",
1073
"game.ap": "行动点",
1074
"game.range": "射程",
1075
"game.you": "你",
1076
"game.dead": "已淘汰",
1077
"game.surrendered": "已投降",
1078
"game.winner": "{name} 获胜!",
1079
"game.youWin": "你赢了!",
1080
"game.draw": "本局以平局结束。",
1081
"game.shrinkIn": "战场将在 {n} 天后缩小",
1082
"game.shrinkInDays.one": "战场将在 {n} 天后缩小",
1083
"game.shrinkInDays.other": "战场将在 {n} 天后缩小",
1084
"game.shrinkInDays.few": "战场将在 {n} 天后缩小",
1085
"game.shrinkInDays.many": "战场将在 {n} 天后缩小",
1086
"game.shrinkTomorrow": "战场将在明天缩小",
1087
"game.shrinkToday": "战场将在下次发放时缩小",
1088
"game.upgrade": "提升射程",
1089
"game.settings": "设置",
1090
"game.surrender": "投降",
1091
"game.surrenderConfirm": "确定投降?你将退出本局,且无法撤销。",
1092
"game.surrenderConfirmBtn": "是的,投降",
1093
"game.surrenderCancel": "取消",
1094
"game.back": "返回菜单",
1095
"game.spectating": "你已被淘汰。你仍可观战、发送消息,并在陪审团开启时投票。",
1096
"game.ceasefireLeft": "停火剩余时间",
1097
"game.ceasefireUntil": "距离停火",
1098
"game.ceasefireActive": "停火中",
1099
"game.attackDisabled": "攻击",
1100
"game.attackDisabledReason": "停火时段内不得攻击。",
1101
"game.selectSelf": "已选中你的坦克。点按高亮格子移动,或提升射程。",
1102
"game.impassable": "不可通行",
1103
"game.willShrink": "下一圈将缩小",
1104
"opt.info": "信息",
1105
"opt.attack": "攻击",
1106
"opt.give": "给予行动点",
1107
"opt.message": "发送消息",
1108
"opt.close": "关闭",
1109
"info.title": "信息",
1110
"info.lives": "生命",
1111
"info.ap": "行动点",
1112
"info.range": "射程",
1113
"info.notes": "你的私人备注",
1114
"info.notesHint": "只有你能看到这些备注。它们保存在你的账户中。",
1115
"info.saveNotes": "保存备注",
1116
"info.saved": "已保存",
1117
"give.title": "给予行动点",
1118
"give.howMany": "给多少?",
1119
"give.send": "给予",
1120
"give.youHave": "你有 {n} 点。",
1121
"chat.title": "给 {name} 的消息",
1122
"chat.placeholder": "写一条私人消息…",
1123
"chat.send": "发送",
1124
"chat.empty": "还没有消息。",
1125
"jury.title": "陪审团",
1126
"jury.hint": "为一名仍存活的玩家投票。得票最多者在下次发放时额外获得 1 点行动点。在此之前可以改票。其他玩家看不到你的投票。",
1127
"jury.vote": "投票",
1128
"jury.votedFor": "你把票投给了 {name}",
1129
"jury.change": "改票",
1130
"timeline.play": "播放",
1131
"timeline.pause": "暂停",
1132
"timeline.live": "实时",
1133
"timeline.event.start": "游戏开始",
1134
"timeline.event.move": "{name} 移动了",
1135
"timeline.event.shoot": "{name} 向 {target} 射击",
1136
"timeline.event.give": "{name} 将 {n} 点行动点给了 {target}",
1137
"timeline.event.upgrade": "{name} 将射程提升到 {n}",
1138
"timeline.event.surrender": "{name} 投降了",
1139
"timeline.event.daily": "第 {n} 天:发放行动点",
1140
"timeline.event.jury": "陪审团将奖励发给 {name}",
1141
"timeline.event.juryTie": "陪审团将奖励发给 {names}",
1142
"timeline.event.shrink": "战场缩小了",
1143
"timeline.event.win": "{name} 获胜",
1144
"timeline.event.death": "{name} 被淘汰",
1145
"timeline.event.deathShot": "{name} 被 {by} 击倒",
1146
"timeline.event.deathShrink": "{name} 被缩小的战场波及",
1147
"timeline.event.deathCrushed": "{name} 被挤出:没有空余格子",
1148
"timeline.event.draw": "本局以平局结束",
1149
"auth.unavailable": "登录暂时不可用。",
1150
"auth.backToGame": "返回 Allianties",
1151
"auth.failed": "登录失败。",
1152
"auth.retry": "重试",
1153
"auth.back": "返回",
1154
"lang.choose": "选择语言",
1155
"lang.current": "语言:{name}",
1156
"error.login": "请登录后再继续。",
1157
"error.csrf": "会话已过期。请刷新页面后再试。",
1158
"error.not_host": "只有房主可以这样做。",
1159
"error.min_players": "至少需要两名玩家才能开始。",
1160
"error.not_in_game": "你不在这局游戏中。",
1161
"error.dead": "你已从本局淘汰。",
1162
"error.no_ap": "你没有剩余的行动点。",
1163
"error.occupied": "该格子已被占用。",
1164
"error.impassable": "该格子不可通行。",
1165
"error.out_of_range": "该玩家超出射程。",
1166
"error.invalid_move": "不允许这样行动。",
1167
"error.game_started": "这局游戏已经开始。",
1168
"error.game_finished": "这局游戏已经结束。",
1169
"error.lobby_full": "此大厅已满。",
1170
"error.unknown_code": "找不到该代码对应的大厅。",
1171
"error.cannot_vote": "你现在不能投票。",
1172
"error.bad_vote": "只能为仍存活的玩家投票。",
1173
"error.bad_give": "不能给予那么多行动点。",
1174
"error.unknown_action": "未知操作。",
1175
"error.ceasefire": "停火时段内不能攻击。",
1176
"error.generic": "出了点问题,请再试一次。",
1177
"error.serverStatus": "服务器返回了 {status}。",
1178
}
1179
1180
KO = {
1181
"app.name": NAME,
1182
"menu.tagline": "인내와 동맹, 그리고 때를 놓치지 않는 사격의 게임.",
1183
"menu.login": "로그인",
1184
"menu.logout": "로그아웃",
1185
"menu.loggedInAs": "로그인됨",
1186
"menu.localTest": "로컬 테스트:",
1187
"menu.create": "새 로비",
1188
"menu.join": "참가",
1189
"menu.codePlaceholder": "코드",
1190
"menu.myGames": "내 게임",
1191
"menu.noGames": "아직 게임이 없습니다. 로비를 만들고 다른 사람을 초대하세요.",
1192
"menu.authUnconfiguredHtml": "이 서버에는 아직 로그인이 설정되지 않았습니다. 콜백 <code>/allianties/callback.php</code>를 auth.timfalken.com에 등록하고 클라이언트 비밀키를 설정해야 합니다.",
1193
"menu.guestHint": "로그인하면 로비를 만들고, 플레이어를 초대하고, 오래 이어지는 게임을 시작할 수 있습니다.",
1194
"menu.open": "열기",
1195
"menu.continue": "계속",
1196
"menu.statusLobby": "로비",
1197
"menu.statusRunning": "진행 중",
1198
"menu.statusFinished": "종료",
1199
"menu.youWon": "승리",
1200
"menu.draw": "무승부",
1201
"menu.winnerIs": "승자: {name}",
1202
"menu.needLogin": "플레이하려면 먼저 로그인하세요.",
1203
"menu.players": "플레이어",
1204
"lobby.title": "로비",
1205
"lobby.invite": "초대",
1206
"lobby.copy": "링크 복사",
1207
"lobby.copied": "복사됨",
1208
"lobby.shareHint": "이 코드나 링크를 공유하세요. 플레이어는 로그인한 뒤 참가합니다.",
1209
"lobby.players": "플레이어",
1210
"lobby.start": "게임 시작",
1211
"lobby.leave": "로비 나가기",
1212
"lobby.host": "호스트",
1213
"lobby.you": "나",
1214
"lobby.minPlayers": "시작하려면 플레이어가 최소 두 명 필요합니다.",
1215
"lobby.needTwo": "플레이어를 최소 한 명 더 기다리는 중…",
1216
"lobby.rules": "규칙",
1217
"lobby.jury": "배심",
1218
"lobby.juryHint": "탈락한 플레이어는 매일 생존 중인 플레이어 한 명에게 투표합니다. 가장 많은 표를 받은 플레이어는 다음 일일 지급 때 행동력을 하나 더 받습니다. 동점이면 동점인 전원에게 보너스가 갑니다. 표는 비밀이며 지급 전까지 바꿀 수 있습니다.",
1219
"lobby.shrink": "줄어드는 전장",
1220
"lobby.shrinkHint": "설정한 일수가 지나면 일일 지급 때 바깥 고리가 통과 불가가 됩니다. 그 위에 있는 플레이어는 목숨을 하나 잃고 안쪽으로 밀립니다.",
1221
"lobby.shrinkDays": "축소 간격(일)",
1222
"lobby.shrinkDaysHint": "첫 축소는 그 횟수만큼의 자정이 지난 뒤, 이후 같은 일수마다 반복되며 전장이 최소 크기에 이를 때까지 계속됩니다.",
1223
"lobby.ceasefire": "강제 휴전 시간",
1224
"lobby.ceasefireHint": "이 시간대(Europe/Amsterdam)에는 아무도 발사할 수 없습니다. 이동, 행동력 전달, 사거리 강화는 가능합니다. 구간은 자정을 넘길 수 있습니다.",
1225
"lobby.ceasefireAdd": "구간 추가",
1226
"lobby.ceasefireRemove": "삭제",
1227
"lobby.ceasefireStart": "시작",
1228
"lobby.ceasefireEnd": "종료",
1229
"lobby.ceasefireEmpty": "아직 구간이 없습니다. 하나를 추가하거나 시계에서 부채꼴을 드래그하세요.",
1230
"lobby.ceasefireClock": "24시간 시계. 핸들을 드래그하거나 부채꼴을 그리세요. 빨강은 휴전, 금색은 사격 가능. 시각은 Europe/Amsterdam입니다.",
1231
"lobby.waiting": "호스트가 게임을 시작하기를 기다리는 중.",
1232
"lobby.back": "뒤로",
1233
"lobby.code": "코드",
1234
"lobby.playerCount.one": "플레이어 {n}명",
1235
"lobby.playerCount.other": "플레이어 {n}명",
1236
"lobby.playerCount.few": "플레이어 {n}명",
1237
"lobby.playerCount.many": "플레이어 {n}명",
1238
"game.day": "{n}일차",
1239
"game.nextAp": "다음 행동력",
1240
"game.lives": "목숨",
1241
"game.ap": "행동력",
1242
"game.range": "사거리",
1243
"game.you": "나",
1244
"game.dead": "탈락",
1245
"game.surrendered": "항복함",
1246
"game.winner": "{name} 승리!",
1247
"game.youWin": "당신이 이겼습니다!",
1248
"game.draw": "게임이 무승부로 끝났습니다.",
1249
"game.shrinkIn": "전장이 {n}일 후 줄어듭니다",
1250
"game.shrinkInDays.one": "전장이 {n}일 후 줄어듭니다",
1251
"game.shrinkInDays.other": "전장이 {n}일 후 줄어듭니다",
1252
"game.shrinkInDays.few": "전장이 {n}일 후 줄어듭니다",
1253
"game.shrinkInDays.many": "전장이 {n}일 후 줄어듭니다",
1254
"game.shrinkTomorrow": "전장이 내일 줄어듭니다",
1255
"game.shrinkToday": "전장이 다음 지급 때 줄어듭니다",
1256
"game.upgrade": "사거리 강화",
1257
"game.settings": "설정",
1258
"game.surrender": "항복",
1259
"game.surrenderConfirm": "항복할까요? 이 게임에서 탈락하며 되돌릴 수 없습니다.",
1260
"game.surrenderConfirmBtn": "네, 항복합니다",
1261
"game.surrenderCancel": "취소",
1262
"game.back": "메뉴로 돌아가기",
1263
"game.spectating": "탈락했습니다. 관전, 메시지 보내기, 배심이 켜져 있다면 투표는 계속할 수 있습니다.",
1264
"game.ceasefireLeft": "휴전 남은 시간",
1265
"game.ceasefireUntil": "휴전까지",
1266
"game.ceasefireActive": "휴전 중",
1267
"game.attackDisabled": "공격",
1268
"game.attackDisabledReason": "휴전 시간에는 공격할 수 없습니다.",
1269
"game.selectSelf": "내 전차가 선택되었습니다. 강조된 칸을 눌러 이동하거나 사거리를 강화하세요.",
1270
"game.impassable": "통과 불가",
1271
"game.willShrink": "다음에 줄어들 고리",
1272
"opt.info": "정보",
1273
"opt.attack": "공격",
1274
"opt.give": "행동력 주기",
1275
"opt.message": "메시지 보내기",
1276
"opt.close": "닫기",
1277
"info.title": "정보",
1278
"info.lives": "목숨",
1279
"info.ap": "행동력",
1280
"info.range": "사거리",
1281
"info.notes": "나만 보는 메모",
1282
"info.notesHint": "이 메모는 당신만 볼 수 있습니다. 계정에 저장됩니다.",
1283
"info.saveNotes": "메모 저장",
1284
"info.saved": "저장됨",
1285
"give.title": "행동력 주기",
1286
"give.howMany": "몇 개?",
1287
"give.send": "주기",
1288
"give.youHave": "{n}개를 가지고 있습니다.",
1289
"chat.title": "{name}에게 메시지",
1290
"chat.placeholder": "비공개 메시지를 작성하세요…",
1291
"chat.send": "보내기",
1292
"chat.empty": "아직 메시지가 없습니다.",
1293
"jury.title": "배심",
1294
"jury.hint": "생존 중인 플레이어 한 명에게 투표하세요. 가장 많은 표를 받은 사람은 다음 지급 때 행동력을 하나 더 받습니다. 그 전까지 표를 바꿀 수 있습니다. 다른 플레이어는 당신의 표를 볼 수 없습니다.",
1295
"jury.vote": "투표",
1296
"jury.votedFor": "{name}에게 투표했습니다",
1297
"jury.change": "투표 변경",
1298
"timeline.play": "재생",
1299
"timeline.pause": "일시정지",
1300
"timeline.live": "실시간",
1301
"timeline.event.start": "게임이 시작됩니다",
1302
"timeline.event.move": "{name}이(가) 이동합니다",
1303
"timeline.event.shoot": "{name}이(가) {target}을(를) 공격합니다",
1304
"timeline.event.give": "{name}이(가) {target}에게 행동력 {n}개를 줍니다",
1305
"timeline.event.upgrade": "{name}이(가) 사거리를 {n}(으)로 올립니다",
1306
"timeline.event.surrender": "{name}이(가) 항복합니다",
1307
"timeline.event.daily": "{n}일차: 행동력 지급",
1308
"timeline.event.jury": "배심이 {name}에게 보너스를 줍니다",
1309
"timeline.event.juryTie": "배심이 {names}에게 보너스를 줍니다",
1310
"timeline.event.shrink": "전장이 줄어듭니다",
1311
"timeline.event.win": "{name} 승리",
1312
"timeline.event.death": "{name} 탈락",
1313
"timeline.event.deathShot": "{name}이(가) {by}에게 피격되어 탈락",
1314
"timeline.event.deathShrink": "{name}이(가) 줄어드는 전장에 걸렸습니다",
1315
"timeline.event.deathCrushed": "{name}이(가) 깔렸습니다: 빈 칸이 없습니다",
1316
"timeline.event.draw": "게임이 무승부로 끝납니다",
1317
"auth.unavailable": "로그인을 잠시 사용할 수 없습니다.",
1318
"auth.backToGame": "Allianties로 돌아가기",
1319
"auth.failed": "로그인에 실패했습니다.",
1320
"auth.retry": "다시 시도",
1321
"auth.back": "뒤로",
1322
"lang.choose": "언어 선택",
1323
"lang.current": "언어: {name}",
1324
"error.login": "계속하려면 로그인하세요.",
1325
"error.csrf": "세션이 만료되었습니다. 페이지를 새로 고친 뒤 다시 시도하세요.",
1326
"error.not_host": "호스트만 할 수 있습니다.",
1327
"error.min_players": "시작하려면 플레이어가 최소 두 명 필요합니다.",
1328
"error.not_in_game": "이 게임에 들어가 있지 않습니다.",
1329
"error.dead": "이 게임에서 탈락했습니다.",
1330
"error.no_ap": "남은 행동력이 없습니다.",
1331
"error.occupied": "그 칸은 이미 차지되어 있습니다.",
1332
"error.impassable": "그 칸은 통과할 수 없습니다.",
1333
"error.out_of_range": "그 플레이어는 사거리 밖입니다.",
1334
"error.invalid_move": "그 행동은 허용되지 않습니다.",
1335
"error.game_started": "이 게임은 이미 시작되었습니다.",
1336
"error.game_finished": "이 게임은 이미 끝났습니다.",
1337
"error.lobby_full": "이 로비는 가득 찼습니다.",
1338
"error.unknown_code": "그 코드의 로비를 찾을 수 없습니다.",
1339
"error.cannot_vote": "지금은 투표할 수 없습니다.",
1340
"error.bad_vote": "생존 중인 플레이어에게만 투표할 수 있습니다.",
1341
"error.bad_give": "그만큼의 행동력은 줄 수 없습니다.",
1342
"error.unknown_action": "알 수 없는 행동입니다.",
1343
"error.ceasefire": "휴전 시간에는 공격할 수 없습니다.",
1344
"error.generic": "문제가 발생했습니다. 다시 시도해 주세요.",
1345
"error.serverStatus": "서버가 {status}을(를) 반환했습니다.",
1346
}
@@ -0,0 +1,1346 @@1
# -*- coding: utf-8 -*-2
NAME = "Allianties"3
4
DE = {5
"app.name": NAME,6
"menu.tagline": "Ein Spiel aus Geduld, Allianzen und gut getimten Schüssen.",7
"menu.login": "Anmelden",8
"menu.logout": "Abmelden",9
"menu.loggedInAs": "Angemeldet als",10
"menu.localTest": "lokaler Test:",11
"menu.create": "Neue Lobby",12
"menu.join": "Beitreten",13
"menu.codePlaceholder": "Code",14
"menu.myGames": "Deine Spiele",15
"menu.noGames": "Du hast noch keine Spiele. Eröffne eine Lobby und lade andere ein.",16
"menu.authUnconfiguredHtml": "Die Anmeldung ist auf diesem Server noch nicht eingerichtet. Der Callback <code>/allianties/callback.php</code> muss bei auth.timfalken.com registriert und das Client-Geheimnis konfiguriert werden.",17
"menu.guestHint": "Melde dich an, um eine Lobby zu erstellen, Spieler einzuladen und ein dauerhaftes Spiel zu starten.",18
"menu.open": "Öffnen",19
"menu.continue": "Weiter",20
"menu.statusLobby": "Lobby",21
"menu.statusRunning": "Läuft",22
"menu.statusFinished": "Beendet",23
"menu.youWon": "Du hast gewonnen",24
"menu.draw": "Unentschieden",25
"menu.winnerIs": "Gewinner: {name}",26
"menu.needLogin": "Melde dich zuerst an, um zu spielen.",27
"menu.players": "Spieler",28
"lobby.title": "Lobby",29
"lobby.invite": "Einladen",30
"lobby.copy": "Link kopieren",31
"lobby.copied": "Kopiert",32
"lobby.shareHint": "Teile diesen Code oder Link. Spieler melden sich an und treten bei.",33
"lobby.players": "Spieler",34
"lobby.start": "Spiel starten",35
"lobby.leave": "Lobby verlassen",36
"lobby.host": "Gastgeber",37
"lobby.you": "du",38
"lobby.minPlayers": "Du brauchst mindestens zwei Spieler, um zu starten.",39
"lobby.needTwo": "Warte auf mindestens einen weiteren Spieler…",40
"lobby.rules": "Regeln",41
"lobby.jury": "Jury",42
"lobby.juryHint": "Tote Spieler stimmen täglich für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten täglichen Verteilung einen Extra-Aktionspunkt. Bei Gleichstand erhält jeder gleichauf liegende Spieler den Bonus. Stimmen sind geheim und bis dahin änderbar.",43
"lobby.shrink": "Schrumpfendes Spielfeld",44
"lobby.shrinkHint": "Nach einer festgelegten Anzahl von Tagen wird der äußere Ring bei der täglichen Verteilung unpassierbar. Spieler, die darauf stehen, verlieren ein Leben und werden nach innen geschoben.",45
"lobby.shrinkDays": "Tage zwischen Schrumpfungen",46
"lobby.shrinkDaysHint": "Erste Schrumpfung nach so vielen Mitternächten, danach erneut nach jeweils ebenso vielen Tagen, bis das Feld seine Mindestgröße erreicht.",47
"lobby.ceasefire": "Erzwungene Waffenruhe",48
"lobby.ceasefireHint": "In diesen Stunden (Europe/Amsterdam) darf niemand schießen. Bewegen, Aktionspunkte abgeben und die Reichweite erhöhen bleiben erlaubt. Zeiträume dürfen über Mitternacht gehen.",49
"lobby.ceasefireAdd": "Zeitraum hinzufügen",50
"lobby.ceasefireRemove": "Entfernen",51
"lobby.ceasefireStart": "Von",52
"lobby.ceasefireEnd": "Bis",53
"lobby.ceasefireEmpty": "Noch keine Zeiträume. Füge einen hinzu oder ziehe ein Segment auf der Uhr.",54
"lobby.ceasefireClock": "24-Stunden-Uhr. Ziehe die Griffe oder male ein Segment; rot ist Waffenruhe, gold ist Feuer frei. Zeiten sind Europe/Amsterdam.",55
"lobby.waiting": "Warte, bis der Gastgeber das Spiel startet.",56
"lobby.back": "Zurück",57
"lobby.code": "Code",58
"lobby.playerCount.one": "{n} Spieler",59
"lobby.playerCount.other": "{n} Spieler",60
"lobby.playerCount.few": "{n} Spieler",61
"lobby.playerCount.many": "{n} Spieler",62
"game.day": "Tag {n}",63
"game.nextAp": "Nächste Aktionspunkte",64
"game.lives": "Leben",65
"game.ap": "Aktionspunkte",66
"game.range": "Reichweite",67
"game.you": "Du",68
"game.dead": "Ausgeschieden",69
"game.surrendered": "Aufgegeben",70
"game.winner": "{name} gewinnt!",71
"game.youWin": "Du gewinnst!",72
"game.draw": "Das Spiel endet unentschieden.",73
"game.shrinkIn": "Das Feld schrumpft in {n} Tagen",74
"game.shrinkInDays.one": "Das Feld schrumpft in {n} Tag",75
"game.shrinkInDays.other": "Das Feld schrumpft in {n} Tagen",76
"game.shrinkInDays.few": "Das Feld schrumpft in {n} Tagen",77
"game.shrinkInDays.many": "Das Feld schrumpft in {n} Tagen",78
"game.shrinkTomorrow": "Das Feld schrumpft morgen",79
"game.shrinkToday": "Das Feld schrumpft bei der nächsten Verteilung",80
"game.upgrade": "Reichweite erhöhen",81
"game.settings": "Einstellungen",82
"game.surrender": "Aufgeben",83
"game.surrenderConfirm": "Aufgeben? Du scheidest aus diesem Spiel aus. Das lässt sich nicht rückgängig machen.",84
"game.surrenderConfirmBtn": "Ja, aufgeben",85
"game.surrenderCancel": "Abbrechen",86
"game.back": "Zurück zum Menü",87
"game.spectating": "Du bist ausgeschieden. Du kannst weiterhin zuschauen, Nachrichten senden und, wenn die Jury an ist, abstimmen.",88
"game.ceasefireLeft": "Verbleibende Waffenruhe",89
"game.ceasefireUntil": "Zeit bis zur Waffenruhe",90
"game.ceasefireActive": "Waffenruhe",91
"game.attackDisabled": "Angreifen",92
"game.attackDisabledReason": "Angreifen ist während der Waffenruhe nicht erlaubt.",93
"game.selectSelf": "Dein Panzer ist ausgewählt. Tippe auf ein markiertes Feld, um dich zu bewegen, oder erhöhe deine Reichweite.",94
"game.impassable": "Unpassierbar",95
"game.willShrink": "Dieser Ring schrumpft als Nächstes",96
"opt.info": "Info",97
"opt.attack": "Angreifen",98
"opt.give": "Aktionspunkte geben",99
"opt.message": "Nachricht senden",100
"opt.close": "Schließen",101
"info.title": "Info",102
"info.lives": "Leben",103
"info.ap": "Aktionspunkte",104
"info.range": "Reichweite",105
"info.notes": "Deine privaten Notizen",106
"info.notesHint": "Nur du kannst diese Notizen sehen. Sie werden bei deinem Konto gespeichert.",107
"info.saveNotes": "Notizen speichern",108
"info.saved": "Gespeichert",109
"give.title": "Aktionspunkte geben",110
"give.howMany": "Wie viele?",111
"give.send": "Geben",112
"give.youHave": "Du hast {n}.",113
"chat.title": "Nachricht an {name}",114
"chat.placeholder": "Schreibe eine private Nachricht…",115
"chat.send": "Senden",116
"chat.empty": "Noch keine Nachrichten.",117
"jury.title": "Jury",118
"jury.hint": "Stimme für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten Verteilung einen Extra-Aktionspunkt. Du kannst deine Stimme bis dahin ändern. Andere Spieler sehen deine Stimme nicht.",119
"jury.vote": "Abstimmen",120
"jury.votedFor": "Du hast für {name} gestimmt",121
"jury.change": "Stimme ändern",122
"timeline.play": "Abspielen",123
"timeline.pause": "Pause",124
"timeline.live": "Live",125
"timeline.event.start": "Das Spiel beginnt",126
"timeline.event.move": "{name} bewegt sich",127
"timeline.event.shoot": "{name} schießt auf {target}",128
"timeline.event.give": "{name} gibt {n} Aktionspunkt(e) an {target}",129
"timeline.event.upgrade": "{name} erhöht die Reichweite auf {n}",130
"timeline.event.surrender": "{name} gibt auf",131
"timeline.event.daily": "Tag {n}: Aktionspunkte werden verteilt",132
"timeline.event.jury": "Die Jury vergibt einen Bonus an {name}",133
"timeline.event.juryTie": "Die Jury vergibt einen Bonus an {names}",134
"timeline.event.shrink": "Das Spielfeld schrumpft",135
"timeline.event.win": "{name} gewinnt",136
"timeline.event.death": "{name} scheidet aus",137
"timeline.event.deathShot": "{name} wird von {by} erschossen",138
"timeline.event.deathShrink": "{name} wird vom schrumpfenden Feld erfasst",139
"timeline.event.deathCrushed": "{name} wird zerdrückt: kein freies Feld mehr",140
"timeline.event.draw": "Das Spiel endet unentschieden",141
"auth.unavailable": "Die Anmeldung ist vorübergehend nicht verfügbar.",142
"auth.backToGame": "Zurück zu Allianties",143
"auth.failed": "Anmeldung fehlgeschlagen.",144
"auth.retry": "Erneut versuchen",145
"auth.back": "Zurück",146
"lang.choose": "Sprache wählen",147
"lang.current": "Sprache: {name}",148
"error.login": "Melde dich an, um fortzufahren.",149
"error.csrf": "Deine Sitzung ist abgelaufen. Aktualisiere die Seite und versuche es erneut.",150
"error.not_host": "Das kann nur der Gastgeber tun.",151
"error.min_players": "Du brauchst mindestens zwei Spieler, um zu starten.",152
"error.not_in_game": "Du bist nicht in diesem Spiel.",153
"error.dead": "Du bist aus diesem Spiel ausgeschieden.",154
"error.no_ap": "Du hast keine Aktionspunkte mehr.",155
"error.occupied": "Dieses Feld ist besetzt.",156
"error.impassable": "Dieses Feld ist unpassierbar.",157
"error.out_of_range": "Dieser Spieler ist außer Reichweite.",158
"error.invalid_move": "Dieser Zug ist nicht erlaubt.",159
"error.game_started": "Dieses Spiel hat bereits begonnen.",160
"error.game_finished": "Dieses Spiel ist beendet.",161
"error.lobby_full": "Diese Lobby ist voll.",162
"error.unknown_code": "Keine Lobby mit diesem Code gefunden.",163
"error.cannot_vote": "Du kannst jetzt nicht abstimmen.",164
"error.bad_vote": "Du kannst nur für einen lebenden Spieler stimmen.",165
"error.bad_give": "So viele Aktionspunkte kannst du nicht abgeben.",166
"error.unknown_action": "Unbekannte Aktion.",167
"error.ceasefire": "Während der Waffenruhe kannst du nicht angreifen.",168
"error.generic": "Etwas ist schiefgegangen. Bitte versuche es erneut.",169
"error.serverStatus": "Der Server antwortete mit {status}.",170
}171
172
FR = {173
"app.name": NAME,174
"menu.tagline": "Un jeu de patience, d'alliances et de tirs bien calculés.",175
"menu.login": "Connexion",176
"menu.logout": "Déconnexion",177
"menu.loggedInAs": "Connecté en tant que",178
"menu.localTest": "test local :",179
"menu.create": "Nouveau salon",180
"menu.join": "Rejoindre",181
"menu.codePlaceholder": "Code",182
"menu.myGames": "Vos parties",183
"menu.noGames": "Vous n'avez pas encore de partie. Créez un salon et invitez d'autres joueurs.",184
"menu.authUnconfiguredHtml": "La connexion n'est pas encore configurée sur ce serveur. Le callback <code>/allianties/callback.php</code> doit être enregistré sur auth.timfalken.com, et le secret client doit être défini.",185
"menu.guestHint": "Connectez-vous pour créer un salon, inviter des joueurs et lancer une partie durable.",186
"menu.open": "Ouvrir",187
"menu.continue": "Continuer",188
"menu.statusLobby": "Salon",189
"menu.statusRunning": "En cours",190
"menu.statusFinished": "Terminée",191
"menu.youWon": "Vous avez gagné",192
"menu.draw": "Match nul",193
"menu.winnerIs": "Vainqueur : {name}",194
"menu.needLogin": "Connectez-vous d'abord pour jouer.",195
"menu.players": "Joueurs",196
"lobby.title": "Salon",197
"lobby.invite": "Inviter",198
"lobby.copy": "Copier le lien",199
"lobby.copied": "Copié",200
"lobby.shareHint": "Partagez ce code ou ce lien. Les joueurs se connectent et rejoignent la partie.",201
"lobby.players": "Joueurs",202
"lobby.start": "Lancer la partie",203
"lobby.leave": "Quitter le salon",204
"lobby.host": "Hôte",205
"lobby.you": "vous",206
"lobby.minPlayers": "Il faut au moins deux joueurs pour commencer.",207
"lobby.needTwo": "En attente d'au moins un joueur de plus…",208
"lobby.rules": "Règles",209
"lobby.jury": "Jury",210
"lobby.juryHint": "Les joueurs éliminés votent chaque jour pour un joueur vivant. Celui qui recueille le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution quotidienne. En cas d'égalité, chaque joueur à égalité reçoit le bonus. Les votes sont secrets et modifiables jusque-là.",211
"lobby.shrink": "Arène rétrécissante",212
"lobby.shrinkHint": "Après un nombre de jours réglable, l'anneau extérieur devient infranchissable à la distribution quotidienne. Les joueurs qui s'y trouvent perdent une vie et sont poussés vers l'intérieur.",213
"lobby.shrinkDays": "Jours entre les rétrécissements",214
"lobby.shrinkDaysHint": "Premier rétrécissement après autant de minuits, puis de nouveau tous les autant de jours, jusqu'à la taille minimale de l'arène.",215
"lobby.ceasefire": "Heures de cessez-le-feu forcé",216
"lobby.ceasefireHint": "Pendant ces heures (Europe/Amsterdam), personne ne peut tirer. Se déplacer, donner des points d'action et améliorer la portée restent autorisés. Les plages peuvent chevaucher minuit.",217
"lobby.ceasefireAdd": "Ajouter une plage",218
"lobby.ceasefireRemove": "Supprimer",219
"lobby.ceasefireStart": "De",220
"lobby.ceasefireEnd": "À",221
"lobby.ceasefireEmpty": "Aucune plage pour l'instant. Ajoutez-en une, ou dessinez un secteur sur l'horloge.",222
"lobby.ceasefireClock": "Horloge 24 heures. Faites glisser les poignées ou dessinez un secteur ; le rouge est le cessez-le-feu, l'or le feu autorisé. Heures en Europe/Amsterdam.",223
"lobby.waiting": "En attente que l'hôte lance la partie.",224
"lobby.back": "Retour",225
"lobby.code": "Code",226
"lobby.playerCount.one": "{n} joueur",227
"lobby.playerCount.other": "{n} joueurs",228
"lobby.playerCount.few": "{n} joueurs",229
"lobby.playerCount.many": "{n} joueurs",230
"game.day": "Jour {n}",231
"game.nextAp": "Prochains points d'action",232
"game.lives": "Vies",233
"game.ap": "Points d'action",234
"game.range": "Portée",235
"game.you": "Vous",236
"game.dead": "Éliminé",237
"game.surrendered": "A abandonné",238
"game.winner": "{name} gagne !",239
"game.youWin": "Vous gagnez !",240
"game.draw": "La partie se termine par un match nul.",241
"game.shrinkIn": "L'arène rétrécit dans {n} jours",242
"game.shrinkInDays.one": "L'arène rétrécit dans {n} jour",243
"game.shrinkInDays.other": "L'arène rétrécit dans {n} jours",244
"game.shrinkInDays.few": "L'arène rétrécit dans {n} jours",245
"game.shrinkInDays.many": "L'arène rétrécit dans {n} jours",246
"game.shrinkTomorrow": "L'arène rétrécit demain",247
"game.shrinkToday": "L'arène rétrécit à la prochaine distribution",248
"game.upgrade": "Augmenter la portée",249
"game.settings": "Paramètres",250
"game.surrender": "Abandonner",251
"game.surrenderConfirm": "Abandonner ? Vous serez éliminé de cette partie. Cette action est irréversible.",252
"game.surrenderConfirmBtn": "Oui, abandonner",253
"game.surrenderCancel": "Annuler",254
"game.back": "Retour au menu",255
"game.spectating": "Vous êtes éliminé. Vous pouvez encore regarder, envoyer des messages et, si le jury est actif, voter.",256
"game.ceasefireLeft": "Temps restant de cessez-le-feu",257
"game.ceasefireUntil": "Temps avant le cessez-le-feu",258
"game.ceasefireActive": "Cessez-le-feu",259
"game.attackDisabled": "Attaquer",260
"game.attackDisabledReason": "Attaquer n'est pas autorisé pendant les heures de cessez-le-feu.",261
"game.selectSelf": "Votre tank est sélectionné. Touchez une case mise en évidence pour vous déplacer, ou augmentez votre portée.",262
"game.impassable": "Infranchissable",263
"game.willShrink": "Cet anneau rétrécira ensuite",264
"opt.info": "Infos",265
"opt.attack": "Attaquer",266
"opt.give": "Donner des points d'action",267
"opt.message": "Envoyer un message",268
"opt.close": "Fermer",269
"info.title": "Infos",270
"info.lives": "Vies",271
"info.ap": "Points d'action",272
"info.range": "Portée",273
"info.notes": "Vos notes privées",274
"info.notesHint": "Vous seul pouvez voir ces notes. Elles sont enregistrées avec votre compte.",275
"info.saveNotes": "Enregistrer les notes",276
"info.saved": "Enregistré",277
"give.title": "Donner des points d'action",278
"give.howMany": "Combien ?",279
"give.send": "Donner",280
"give.youHave": "Vous en avez {n}.",281
"chat.title": "Message à {name}",282
"chat.placeholder": "Écrire un message privé…",283
"chat.send": "Envoyer",284
"chat.empty": "Pas encore de messages.",285
"jury.title": "Jury",286
"jury.hint": "Votez pour un joueur vivant. Celui qui obtient le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution. Vous pouvez changer votre vote jusque-là. Les autres joueurs ne voient pas votre vote.",287
"jury.vote": "Voter",288
"jury.votedFor": "Vous avez voté pour {name}",289
"jury.change": "Changer de vote",290
"timeline.play": "Lecture",291
"timeline.pause": "Pause",292
"timeline.live": "En direct",293
"timeline.event.start": "La partie commence",294
"timeline.event.move": "{name} se déplace",295
"timeline.event.shoot": "{name} tire sur {target}",296
"timeline.event.give": "{name} donne {n} point(s) d'action à {target}",297
"timeline.event.upgrade": "{name} porte sa portée à {n}",298
"timeline.event.surrender": "{name} abandonne",299
"timeline.event.daily": "Jour {n} : distribution des points d'action",300
"timeline.event.jury": "Le jury attribue un bonus à {name}",301
"timeline.event.juryTie": "Le jury attribue un bonus à {names}",302
"timeline.event.shrink": "L'arène rétrécit",303
"timeline.event.win": "{name} gagne",304
"timeline.event.death": "{name} est éliminé",305
"timeline.event.deathShot": "{name} est abattu par {by}",306
"timeline.event.deathShrink": "{name} est pris par l'arène qui rétrécit",307
"timeline.event.deathCrushed": "{name} est écrasé : plus aucune case libre",308
"timeline.event.draw": "La partie se termine par un match nul",309
"auth.unavailable": "La connexion est temporairement indisponible.",310
"auth.backToGame": "Retour à Allianties",311
"auth.failed": "Échec de la connexion.",312
"auth.retry": "Réessayer",313
"auth.back": "Retour",314
"lang.choose": "Choisir la langue",315
"lang.current": "Langue : {name}",316
"error.login": "Connectez-vous pour continuer.",317
"error.csrf": "Votre session a expiré. Actualisez la page et réessayez.",318
"error.not_host": "Seul l'hôte peut faire cela.",319
"error.min_players": "Il faut au moins deux joueurs pour commencer.",320
"error.not_in_game": "Vous n'êtes pas dans cette partie.",321
"error.dead": "Vous êtes éliminé de cette partie.",322
"error.no_ap": "Vous n'avez plus de points d'action.",323
"error.occupied": "Cette case est occupée.",324
"error.impassable": "Cette case est infranchissable.",325
"error.out_of_range": "Ce joueur est hors de portée.",326
"error.invalid_move": "Ce coup n'est pas autorisé.",327
"error.game_started": "Cette partie a déjà commencé.",328
"error.game_finished": "Cette partie est terminée.",329
"error.lobby_full": "Ce salon est complet.",330
"error.unknown_code": "Aucun salon trouvé avec ce code.",331
"error.cannot_vote": "Vous ne pouvez pas voter maintenant.",332
"error.bad_vote": "Vous ne pouvez voter que pour un joueur vivant.",333
"error.bad_give": "Vous ne pouvez pas donner autant de points d'action.",334
"error.unknown_action": "Action inconnue.",335
"error.ceasefire": "Vous ne pouvez pas attaquer pendant le cessez-le-feu.",336
"error.generic": "Un problème est survenu. Veuillez réessayer.",337
"error.serverStatus": "Le serveur a renvoyé {status}.",338
}339
340
ES = {341
"app.name": NAME,342
"menu.tagline": "Un juego de paciencia, alianzas y disparos bien calculados.",343
"menu.login": "Iniciar sesión",344
"menu.logout": "Cerrar sesión",345
"menu.loggedInAs": "Sesión iniciada como",346
"menu.localTest": "prueba local:",347
"menu.create": "Nueva sala",348
"menu.join": "Unirse",349
"menu.codePlaceholder": "Código",350
"menu.myGames": "Tus partidas",351
"menu.noGames": "Aún no tienes partidas. Crea una sala e invita a otros.",352
"menu.authUnconfiguredHtml": "El inicio de sesión aún no está configurado en este servidor. Hay que registrar la callback <code>/allianties/callback.php</code> en auth.timfalken.com y configurar el secreto del cliente.",353
"menu.guestHint": "Inicia sesión para crear una sala, invitar jugadores y empezar una partida duradera.",354
"menu.open": "Abrir",355
"menu.continue": "Continuar",356
"menu.statusLobby": "Sala",357
"menu.statusRunning": "En juego",358
"menu.statusFinished": "Terminada",359
"menu.youWon": "Has ganado",360
"menu.draw": "Empate",361
"menu.winnerIs": "Ganador: {name}",362
"menu.needLogin": "Inicia sesión primero para jugar.",363
"menu.players": "Jugadores",364
"lobby.title": "Sala",365
"lobby.invite": "Invitar",366
"lobby.copy": "Copiar enlace",367
"lobby.copied": "Copiado",368
"lobby.shareHint": "Comparte este código o enlace. Los jugadores inician sesión y se unen.",369
"lobby.players": "Jugadores",370
"lobby.start": "Empezar partida",371
"lobby.leave": "Salir de la sala",372
"lobby.host": "Anfitrión",373
"lobby.you": "tú",374
"lobby.minPlayers": "Hacen falta al menos dos jugadores para empezar.",375
"lobby.needTwo": "Esperando al menos a un jugador más…",376
"lobby.rules": "Reglas",377
"lobby.jury": "Jurado",378
"lobby.juryHint": "Los jugadores eliminados votan cada día por un jugador vivo. Quien recibe más votos obtiene un punto de acción extra en el siguiente reparto diario. En caso de empate, cada jugador empatado recibe la bonificación. Los votos son secretos y se pueden cambiar hasta entonces.",379
"lobby.shrink": "Arena que se encoge",380
"lobby.shrinkHint": "Tras un número configurable de días, el anillo exterior se vuelve intransitable en el reparto diario. Los jugadores que estén encima pierden una vida y son empujados hacia dentro.",381
"lobby.shrinkDays": "Días entre encogimientos",382
"lobby.shrinkDaysHint": "El primer encogimiento tras tantas medianoches, y luego cada vez que pasen otros tantos días, hasta el tamaño mínimo de la arena.",383
"lobby.ceasefire": "Horas de alto el fuego forzoso",384
"lobby.ceasefireHint": "Durante estas horas (Europe/Amsterdam) nadie puede disparar. Moverse, dar puntos de acción y mejorar el alcance siguen permitidos. Los periodos pueden cruzar la medianoche.",385
"lobby.ceasefireAdd": "Añadir periodo",386
"lobby.ceasefireRemove": "Quitar",387
"lobby.ceasefireStart": "Desde",388
"lobby.ceasefireEnd": "Hasta",389
"lobby.ceasefireEmpty": "Aún no hay periodos. Añade uno o arrastra un sector en el reloj.",390
"lobby.ceasefireClock": "Reloj de 24 horas. Arrastra los tiradores o pinta un sector; el rojo es alto el fuego, el oro es fuego libre. Horarios en Europe/Amsterdam.",391
"lobby.waiting": "Esperando a que el anfitrión empiece la partida.",392
"lobby.back": "Volver",393
"lobby.code": "Código",394
"lobby.playerCount.one": "{n} jugador",395
"lobby.playerCount.other": "{n} jugadores",396
"lobby.playerCount.few": "{n} jugadores",397
"lobby.playerCount.many": "{n} jugadores",398
"game.day": "Día {n}",399
"game.nextAp": "Próximos puntos de acción",400
"game.lives": "Vidas",401
"game.ap": "Puntos de acción",402
"game.range": "Alcance",403
"game.you": "Tú",404
"game.dead": "Eliminado",405
"game.surrendered": "Se rindió",406
"game.winner": "¡{name} gana!",407
"game.youWin": "¡Has ganado!",408
"game.draw": "La partida termina en empate.",409
"game.shrinkIn": "La arena se encoge en {n} días",410
"game.shrinkInDays.one": "La arena se encoge en {n} día",411
"game.shrinkInDays.other": "La arena se encoge en {n} días",412
"game.shrinkInDays.few": "La arena se encoge en {n} días",413
"game.shrinkInDays.many": "La arena se encoge en {n} días",414
"game.shrinkTomorrow": "La arena se encoge mañana",415
"game.shrinkToday": "La arena se encoge en el siguiente reparto",416
"game.upgrade": "Aumentar alcance",417
"game.settings": "Ajustes",418
"game.surrender": "Rendirse",419
"game.surrenderConfirm": "¿Rendirse? Quedarás fuera de esta partida. No se puede deshacer.",420
"game.surrenderConfirmBtn": "Sí, rendirme",421
"game.surrenderCancel": "Cancelar",422
"game.back": "Volver al menú",423
"game.spectating": "Estás eliminado. Aún puedes observar, enviar mensajes y, si el jurado está activo, votar.",424
"game.ceasefireLeft": "Tiempo restante de alto el fuego",425
"game.ceasefireUntil": "Tiempo hasta el alto el fuego",426
"game.ceasefireActive": "Alto el fuego",427
"game.attackDisabled": "Atacar",428
"game.attackDisabledReason": "No se puede atacar durante las horas de alto el fuego.",429
"game.selectSelf": "Tu tanque está seleccionado. Toca una casilla destacada para moverte, o aumenta tu alcance.",430
"game.impassable": "Intransitable",431
"game.willShrink": "Este anillo se encogerá a continuación",432
"opt.info": "Info",433
"opt.attack": "Atacar",434
"opt.give": "Dar puntos de acción",435
"opt.message": "Enviar mensaje",436
"opt.close": "Cerrar",437
"info.title": "Info",438
"info.lives": "Vidas",439
"info.ap": "Puntos de acción",440
"info.range": "Alcance",441
"info.notes": "Tus notas privadas",442
"info.notesHint": "Solo tú puedes ver estas notas. Se guardan con tu cuenta.",443
"info.saveNotes": "Guardar notas",444
"info.saved": "Guardado",445
"give.title": "Dar puntos de acción",446
"give.howMany": "¿Cuántos?",447
"give.send": "Dar",448
"give.youHave": "Tienes {n}.",449
"chat.title": "Mensaje a {name}",450
"chat.placeholder": "Escribe un mensaje privado…",451
"chat.send": "Enviar",452
"chat.empty": "Aún no hay mensajes.",453
"jury.title": "Jurado",454
"jury.hint": "Vota por un jugador vivo. Quien reciba más votos obtiene un punto de acción extra en el siguiente reparto. Puedes cambiar tu voto hasta entonces. Los demás no ven tu voto.",455
"jury.vote": "Votar",456
"jury.votedFor": "Has votado por {name}",457
"jury.change": "Cambiar voto",458
"timeline.play": "Reproducir",459
"timeline.pause": "Pausa",460
"timeline.live": "En directo",461
"timeline.event.start": "Empieza la partida",462
"timeline.event.move": "{name} se mueve",463
"timeline.event.shoot": "{name} dispara a {target}",464
"timeline.event.give": "{name} da {n} punto(s) de acción a {target}",465
"timeline.event.upgrade": "{name} aumenta el alcance a {n}",466
"timeline.event.surrender": "{name} se rinde",467
"timeline.event.daily": "Día {n}: se reparten los puntos de acción",468
"timeline.event.jury": "El jurado otorga una bonificación a {name}",469
"timeline.event.juryTie": "El jurado otorga una bonificación a {names}",470
"timeline.event.shrink": "La arena se encoge",471
"timeline.event.win": "{name} gana",472
"timeline.event.death": "{name} queda eliminado",473
"timeline.event.deathShot": "{by} dispara a {name} y lo elimina",474
"timeline.event.deathShrink": "{name} es alcanzado por la arena que se encoge",475
"timeline.event.deathCrushed": "{name} queda aplastado: no queda ninguna casilla libre",476
"timeline.event.draw": "La partida termina en empate",477
"auth.unavailable": "El inicio de sesión no está disponible temporalmente.",478
"auth.backToGame": "Volver a Allianties",479
"auth.failed": "Error al iniciar sesión.",480
"auth.retry": "Reintentar",481
"auth.back": "Volver",482
"lang.choose": "Elegir idioma",483
"lang.current": "Idioma: {name}",484
"error.login": "Inicia sesión para continuar.",485
"error.csrf": "Tu sesión ha caducado. Actualiza la página e inténtalo de nuevo.",486
"error.not_host": "Solo el anfitrión puede hacer eso.",487
"error.min_players": "Hacen falta al menos dos jugadores para empezar.",488
"error.not_in_game": "No estás en esta partida.",489
"error.dead": "Has quedado eliminado de esta partida.",490
"error.no_ap": "No te quedan puntos de acción.",491
"error.occupied": "Esa casilla está ocupada.",492
"error.impassable": "Esa casilla es intransitable.",493
"error.out_of_range": "Ese jugador está fuera de alcance.",494
"error.invalid_move": "Ese movimiento no está permitido.",495
"error.game_started": "Esta partida ya ha empezado.",496
"error.game_finished": "Esta partida ha terminado.",497
"error.lobby_full": "Esta sala está llena.",498
"error.unknown_code": "No se encontró ninguna sala con ese código.",499
"error.cannot_vote": "Ahora no puedes votar.",500
"error.bad_vote": "Solo puedes votar por un jugador vivo.",501
"error.bad_give": "No puedes dar tantos puntos de acción.",502
"error.unknown_action": "Acción desconocida.",503
"error.ceasefire": "No puedes atacar durante el alto el fuego.",504
"error.generic": "Algo salió mal. Inténtalo de nuevo.",505
"error.serverStatus": "El servidor devolvió {status}.",506
}507
508
PL = {509
"app.name": NAME,510
"menu.tagline": "Gra cierpliwości, sojuszy i dobrze wycelowanych strzałów.",511
"menu.login": "Zaloguj się",512
"menu.logout": "Wyloguj się",513
"menu.loggedInAs": "Zalogowano jako",514
"menu.localTest": "test lokalny:",515
"menu.create": "Nowe lobby",516
"menu.join": "Dołącz",517
"menu.codePlaceholder": "Kod",518
"menu.myGames": "Twoje gry",519
"menu.noGames": "Nie masz jeszcze żadnych gier. Załóż lobby i zaproś innych.",520
"menu.authUnconfiguredHtml": "Logowanie nie jest jeszcze skonfigurowane na tym serwerze. Callback <code>/allianties/callback.php</code> musi zostać zarejestrowany w auth.timfalken.com, a sekret klienta musi zostać ustawiony.",521
"menu.guestHint": "Zaloguj się, aby utworzyć lobby, zaprosić graczy i rozpocząć trwałą rozgrywkę.",522
"menu.open": "Otwórz",523
"menu.continue": "Kontynuuj",524
"menu.statusLobby": "Lobby",525
"menu.statusRunning": "W toku",526
"menu.statusFinished": "Zakończona",527
"menu.youWon": "Wygrana",528
"menu.draw": "Remis",529
"menu.winnerIs": "Zwycięzca: {name}",530
"menu.needLogin": "Najpierw zaloguj się, aby zagrać.",531
"menu.players": "Gracze",532
"lobby.title": "Lobby",533
"lobby.invite": "Zaproś",534
"lobby.copy": "Kopiuj link",535
"lobby.copied": "Skopiowano",536
"lobby.shareHint": "Udostępnij ten kod lub link. Gracze logują się i dołączają.",537
"lobby.players": "Gracze",538
"lobby.start": "Rozpocznij grę",539
"lobby.leave": "Opuść lobby",540
"lobby.host": "Gospodarz",541
"lobby.you": "ty",542
"lobby.minPlayers": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",543
"lobby.needTwo": "Oczekiwanie na co najmniej jednego gracza…",544
"lobby.rules": "Zasady",545
"lobby.jury": "Jury",546
"lobby.juryHint": "Eliminowani gracze codziennie głosują na żywego gracza. Osoba z największą liczbą głosów otrzymuje dodatkowy punkt akcji przy kolejnym codziennym rozdaniu. Przy remisie bonus dostaje każdy z ex aequo. Głosy są tajne i można je zmieniać do tego momentu.",547
"lobby.shrink": "Kurcząca się arena",548
"lobby.shrinkHint": "Po ustalonej liczbie dni zewnętrzny pierścień staje się nieprzekraczalny przy codziennym rozdaniu. Gracze, którzy na nim stoją, tracą jedno życie i są spychani do środka.",549
"lobby.shrinkDays": "Dni między skurczeniami",550
"lobby.shrinkDaysHint": "Pierwsze skurczenie po tylu północach, potem ponownie co tyle samo dni, aż arena osiągnie minimalny rozmiar.",551
"lobby.ceasefire": "Wymuszone godziny zawieszenia broni",552
"lobby.ceasefireHint": "W tych godzinach (Europe/Amsterdam) nikt nie może strzelać. Ruch, przekazywanie punktów akcji i zwiększanie zasięgu pozostają dozwolone. Zakresy mogą przekraczać północ.",553
"lobby.ceasefireAdd": "Dodaj okres",554
"lobby.ceasefireRemove": "Usuń",555
"lobby.ceasefireStart": "Od",556
"lobby.ceasefireEnd": "Do",557
"lobby.ceasefireEmpty": "Brak okresów. Dodaj jeden albo narysuj wycinek na zegarze.",558
"lobby.ceasefireClock": "Zegar 24-godzinny. Przeciągaj uchwyty lub maluj wycinek; czerwień to zawieszenie broni, złoto to dowolność strzału. Czas: Europe/Amsterdam.",559
"lobby.waiting": "Czekamy, aż gospodarz rozpocznie grę.",560
"lobby.back": "Wstecz",561
"lobby.code": "Kod",562
"lobby.playerCount.one": "{n} gracz",563
"lobby.playerCount.other": "{n} graczy",564
"lobby.playerCount.few": "{n} graczy",565
"lobby.playerCount.many": "{n} graczy",566
"game.day": "Dzień {n}",567
"game.nextAp": "Następne punkty akcji",568
"game.lives": "Życia",569
"game.ap": "Punkty akcji",570
"game.range": "Zasięg",571
"game.you": "Ty",572
"game.dead": "Eliminacja",573
"game.surrendered": "Poddał się",574
"game.winner": "{name} wygrywa!",575
"game.youWin": "Wygrywasz!",576
"game.draw": "Gra kończy się remisem.",577
"game.shrinkIn": "Arena skurczy się za {n} dni",578
"game.shrinkInDays.one": "Arena skurczy się za {n} dzień",579
"game.shrinkInDays.other": "Arena skurczy się za {n} dni",580
"game.shrinkInDays.few": "Arena skurczy się za {n} dni",581
"game.shrinkInDays.many": "Arena skurczy się za {n} dni",582
"game.shrinkTomorrow": "Arena skurczy się jutro",583
"game.shrinkToday": "Arena skurczy się przy następnym rozdaniu",584
"game.upgrade": "Zwiększ zasięg",585
"game.settings": "Ustawienia",586
"game.surrender": "Poddaj się",587
"game.surrenderConfirm": "Poddać się? Odpadniesz z tej gry. Tej czynności nie można cofnąć.",588
"game.surrenderConfirmBtn": "Tak, poddaję się",589
"game.surrenderCancel": "Anuluj",590
"game.back": "Powrót do menu",591
"game.spectating": "Odpadłeś. Nadal możesz oglądać, wysyłać wiadomości i — jeśli jury jest włączone — głosować.",592
"game.ceasefireLeft": "Pozostały czas zawieszenia broni",593
"game.ceasefireUntil": "Czas do zawieszenia broni",594
"game.ceasefireActive": "Zawieszenie broni",595
"game.attackDisabled": "Atak",596
"game.attackDisabledReason": "Atak jest niedozwolony w godzinach zawieszenia broni.",597
"game.selectSelf": "Twój czołg jest zaznaczony. Dotknij podświetlonego pola, aby się ruszyć, albo zwiększ zasięg.",598
"game.impassable": "Nieprzekraczalne",599
"game.willShrink": "Ten pierścień skurczy się jako następny",600
"opt.info": "Informacje",601
"opt.attack": "Atakuj",602
"opt.give": "Przekaż punkty akcji",603
"opt.message": "Wyślij wiadomość",604
"opt.close": "Zamknij",605
"info.title": "Informacje",606
"info.lives": "Życia",607
"info.ap": "Punkty akcji",608
"info.range": "Zasięg",609
"info.notes": "Twoje prywatne notatki",610
"info.notesHint": "Tylko ty widzisz te notatki. Są przechowywane przy twoim koncie.",611
"info.saveNotes": "Zapisz notatki",612
"info.saved": "Zapisano",613
"give.title": "Przekaż punkty akcji",614
"give.howMany": "Ile?",615
"give.send": "Przekaż",616
"give.youHave": "Masz {n}.",617
"chat.title": "Wiadomość do {name}",618
"chat.placeholder": "Napisz prywatną wiadomość…",619
"chat.send": "Wyślij",620
"chat.empty": "Nie ma jeszcze wiadomości.",621
"jury.title": "Jury",622
"jury.hint": "Zagłosuj na jednego żywego gracza. Osoba z największą liczbą głosów otrzyma dodatkowy punkt akcji przy następnym rozdaniu. Do tego czasu możesz zmienić głos. Inni gracze go nie widzą.",623
"jury.vote": "Głosuj",624
"jury.votedFor": "Zagłosowałeś na {name}",625
"jury.change": "Zmień głos",626
"timeline.play": "Odtwórz",627
"timeline.pause": "Pauza",628
"timeline.live": "Na żywo",629
"timeline.event.start": "Gra się zaczyna",630
"timeline.event.move": "{name} się przemieszcza",631
"timeline.event.shoot": "{name} strzela do {target}",632
"timeline.event.give": "{name} przekazuje {n} pkt. akcji dla {target}",633
"timeline.event.upgrade": "{name} zwiększa zasięg do {n}",634
"timeline.event.surrender": "{name} się poddaje",635
"timeline.event.daily": "Dzień {n}: rozdanie punktów akcji",636
"timeline.event.jury": "Jury przyznaje bonus dla {name}",637
"timeline.event.juryTie": "Jury przyznaje bonus dla {names}",638
"timeline.event.shrink": "Arena się kurczy",639
"timeline.event.win": "{name} wygrywa",640
"timeline.event.death": "{name} odpada",641
"timeline.event.deathShot": "{name} zostaje zestrzelony przez {by}",642
"timeline.event.deathShrink": "{name} zostaje złapany przez kurczącą się arenę",643
"timeline.event.deathCrushed": "{name} zostaje zmiażdżony: nie ma wolnego pola",644
"timeline.event.draw": "Gra kończy się remisem",645
"auth.unavailable": "Logowanie jest chwilowo niedostępne.",646
"auth.backToGame": "Powrót do Allianties",647
"auth.failed": "Logowanie nie powiodło się.",648
"auth.retry": "Spróbuj ponownie",649
"auth.back": "Wstecz",650
"lang.choose": "Wybierz język",651
"lang.current": "Język: {name}",652
"error.login": "Zaloguj się, aby kontynuować.",653
"error.csrf": "Twoja sesja wygasła. Odśwież stronę i spróbuj ponownie.",654
"error.not_host": "Tylko gospodarz może to zrobić.",655
"error.min_players": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",656
"error.not_in_game": "Nie jesteś w tej grze.",657
"error.dead": "Odpadłeś z tej gry.",658
"error.no_ap": "Nie masz już punktów akcji.",659
"error.occupied": "To pole jest zajęte.",660
"error.impassable": "To pole jest nieprzekraczalne.",661
"error.out_of_range": "Ten gracz jest poza zasięgiem.",662
"error.invalid_move": "Ten ruch jest niedozwolony.",663
"error.game_started": "Ta gra już się rozpoczęła.",664
"error.game_finished": "Ta gra się zakończyła.",665
"error.lobby_full": "To lobby jest pełne.",666
"error.unknown_code": "Nie znaleziono lobby o takim kodzie.",667
"error.cannot_vote": "Teraz nie możesz głosować.",668
"error.bad_vote": "Możesz głosować tylko na żywego gracza.",669
"error.bad_give": "Nie możesz przekazać tylu punktów akcji.",670
"error.unknown_action": "Nieznana akcja.",671
"error.ceasefire": "Nie możesz atakować w godzinach zawieszenia broni.",672
"error.generic": "Coś poszło nie tak. Spróbuj ponownie.",673
"error.serverStatus": "Serwer zwrócił {status}.",674
}675
676
RU = {677
"app.name": NAME,678
"menu.tagline": "Игра в терпение, союзы и точно timed выстрелы.".replace("точно timed", "хорошо рассчитанные"),679
"menu.login": "Войти",680
"menu.logout": "Выйти",681
"menu.loggedInAs": "Вы вошли как",682
"menu.localTest": "локальный тест:",683
"menu.create": "Новое лобби",684
"menu.join": "Присоединиться",685
"menu.codePlaceholder": "Код",686
"menu.myGames": "Ваши игры",687
"menu.noGames": "У вас пока нет игр. Создайте лобби и пригласите других.",688
"menu.authUnconfiguredHtml": "Вход на этом сервере ещё не настроен. Callback <code>/allianties/callback.php</code> нужно зарегистрировать на auth.timfalken.com, а секрет клиента — задать.",689
"menu.guestHint": "Войдите, чтобы создать лобби, пригласить игроков и начать долгую партию.",690
"menu.open": "Открыть",691
"menu.continue": "Продолжить",692
"menu.statusLobby": "Лобби",693
"menu.statusRunning": "Идёт игра",694
"menu.statusFinished": "Завершена",695
"menu.youWon": "Вы победили",696
"menu.draw": "Ничья",697
"menu.winnerIs": "Победитель: {name}",698
"menu.needLogin": "Сначала войдите, чтобы играть.",699
"menu.players": "Игроки",700
"lobby.title": "Лобби",701
"lobby.invite": "Пригласить",702
"lobby.copy": "Копировать ссылку",703
"lobby.copied": "Скопировано",704
"lobby.shareHint": "Поделитесь этим кодом или ссылкой. Игроки входят в аккаунт и присоединяются.",705
"lobby.players": "Игроки",706
"lobby.start": "Начать игру",707
"lobby.leave": "Покинуть лобби",708
"lobby.host": "Хозяин",709
"lobby.you": "вы",710
"lobby.minPlayers": "Для начала нужно как минимум два игрока.",711
"lobby.needTwo": "Ждём ещё хотя бы одного игрока…",712
"lobby.rules": "Правила",713
"lobby.jury": "Жюри",714
"lobby.juryHint": "Выбывшие игроки каждый день голосуют за живого игрока. Набравший больше всех голосов получает дополнительное очко действия при следующем ежедневном начислении. При ничьей бонус получают все, кто набрал одинаково максимум. Голоса тайные и их можно менять до начисления.",715
"lobby.shrink": "Сжимающаяся арена",716
"lobby.shrinkHint": "Через заданное число дней внешнее кольцо становится непроходимым в момент ежедневного начисления. Игроки, стоящие на нём, теряют одну жизнь и сдвигаются внутрь.",717
"lobby.shrinkDays": "Дней между сжатиями",718
"lobby.shrinkDaysHint": "Первое сжатие после стольких полуночей, затем снова через столько же дней, пока арена не достигнет минимального размера.",719
"lobby.ceasefire": "Принудительное перемирие",720
"lobby.ceasefireHint": "В эти часы (Europe/Amsterdam) стрелять нельзя. Ходить, передавать очки действия и увеличивать дальность по-прежнему можно. Интервалы могут переходить через полночь.",721
"lobby.ceasefireAdd": "Добавить период",722
"lobby.ceasefireRemove": "Удалить",723
"lobby.ceasefireStart": "С",724
"lobby.ceasefireEnd": "До",725
"lobby.ceasefireEmpty": "Периодов пока нет. Добавьте один или нарисуйте сектор на часах.",726
"lobby.ceasefireClock": "24-часовые часы. Перетаскивайте ручки или рисуйте сектор; красный — перемирие, золотой — огонь разрешён. Время: Europe/Amsterdam.",727
"lobby.waiting": "Ждём, пока хозяин начнёт игру.",728
"lobby.back": "Назад",729
"lobby.code": "Код",730
"lobby.playerCount.one": "{n} игрок",731
"lobby.playerCount.other": "{n} игроков",732
"lobby.playerCount.few": "{n} игрока",733
"lobby.playerCount.many": "{n} игроков",734
"game.day": "День {n}",735
"game.nextAp": "Следующие очки действия",736
"game.lives": "Жизни",737
"game.ap": "Очки действия",738
"game.range": "Дальность",739
"game.you": "Вы",740
"game.dead": "Выбыл",741
"game.surrendered": "Сдался",742
"game.winner": "{name} побеждает!",743
"game.youWin": "Вы победили!",744
"game.draw": "Игра заканчивается вничью.",745
"game.shrinkIn": "Арена сожмётся через {n} дн.",746
"game.shrinkInDays.one": "Арена сожмётся через {n} день",747
"game.shrinkInDays.other": "Арена сожмётся через {n} дней",748
"game.shrinkInDays.few": "Арена сожмётся через {n} дня",749
"game.shrinkInDays.many": "Арена сожмётся через {n} дней",750
"game.shrinkTomorrow": "Арена сожмётся завтра",751
"game.shrinkToday": "Арена сожмётся при следующем начислении",752
"game.upgrade": "Увеличить дальность",753
"game.settings": "Настройки",754
"game.surrender": "Сдаться",755
"game.surrenderConfirm": "Сдаться? Вы выбудете из этой игры. Это нельзя отменить.",756
"game.surrenderConfirmBtn": "Да, сдаться",757
"game.surrenderCancel": "Отмена",758
"game.back": "Вернуться в меню",759
"game.spectating": "Вы выбыли. Можно смотреть, писать сообщения и, если жюри включено, голосовать.",760
"game.ceasefireLeft": "До конца перемирия",761
"game.ceasefireUntil": "До начала перемирия",762
"game.ceasefireActive": "Перемирие",763
"game.attackDisabled": "Атака",764
"game.attackDisabledReason": "Во время перемирия атаковать нельзя.",765
"game.selectSelf": "Ваш танк выбран. Нажмите подсвеченную клетку, чтобы пойти, или увеличьте дальность.",766
"game.impassable": "Непроходимо",767
"game.willShrink": "Это кольцо сожмётся следующим",768
"opt.info": "Сведения",769
"opt.attack": "Атаковать",770
"opt.give": "Отдать очки действия",771
"opt.message": "Отправить сообщение",772
"opt.close": "Закрыть",773
"info.title": "Сведения",774
"info.lives": "Жизни",775
"info.ap": "Очки действия",776
"info.range": "Дальность",777
"info.notes": "Ваши личные заметки",778
"info.notesHint": "Эти заметки видите только вы. Они хранятся в вашем аккаунте.",779
"info.saveNotes": "Сохранить заметки",780
"info.saved": "Сохранено",781
"give.title": "Отдать очки действия",782
"give.howMany": "Сколько?",783
"give.send": "Отдать",784
"give.youHave": "У вас {n}.",785
"chat.title": "Сообщение для {name}",786
"chat.placeholder": "Напишите личное сообщение…",787
"chat.send": "Отправить",788
"chat.empty": "Сообщений пока нет.",789
"jury.title": "Жюри",790
"jury.hint": "Голосуйте за одного живого игрока. Набравший больше всех голосов получит дополнительное очко действия при следующем начислении. Голос можно менять до этого момента. Другие игроки его не видят.",791
"jury.vote": "Голосовать",792
"jury.votedFor": "Вы проголосовали за {name}",793
"jury.change": "Изменить голос",794
"timeline.play": "Воспроизвести",795
"timeline.pause": "Пауза",796
"timeline.live": "Сейчас",797
"timeline.event.start": "Игра начинается",798
"timeline.event.move": "{name} перемещается",799
"timeline.event.shoot": "{name} стреляет в {target}",800
"timeline.event.give": "{name} отдаёт {n} очк. действия игроку {target}",801
"timeline.event.upgrade": "{name} увеличивает дальность до {n}",802
"timeline.event.surrender": "{name} сдаётся",803
"timeline.event.daily": "День {n}: начисление очков действия",804
"timeline.event.jury": "Жюри присуждает бонус игроку {name}",805
"timeline.event.juryTie": "Жюри присуждает бонус игрокам {names}",806
"timeline.event.shrink": "Арена сжимается",807
"timeline.event.win": "{name} побеждает",808
"timeline.event.death": "{name} выбывает",809
"timeline.event.deathShot": "{name} подбит игроком {by}",810
"timeline.event.deathShrink": "{name} задевает сжимающаяся арена",811
"timeline.event.deathCrushed": "{name} раздавлен: свободных клеток не осталось",812
"timeline.event.draw": "Игра заканчивается вничью",813
"auth.unavailable": "Вход временно недоступен.",814
"auth.backToGame": "Назад в Allianties",815
"auth.failed": "Не удалось войти.",816
"auth.retry": "Попробовать снова",817
"auth.back": "Назад",818
"lang.choose": "Выберите язык",819
"lang.current": "Язык: {name}",820
"error.login": "Войдите, чтобы продолжить.",821
"error.csrf": "Сессия истекла. Обновите страницу и попробуйте снова.",822
"error.not_host": "Это может сделать только хозяин.",823
"error.min_players": "Для начала нужно как минимум два игрока.",824
"error.not_in_game": "Вас нет в этой игре.",825
"error.dead": "Вы выбыли из этой игры.",826
"error.no_ap": "У вас не осталось очков действия.",827
"error.occupied": "Эта клетка занята.",828
"error.impassable": "Эта клетка непроходима.",829
"error.out_of_range": "Этот игрок вне досягаемости.",830
"error.invalid_move": "Этот ход недопустим.",831
"error.game_started": "Эта игра уже началась.",832
"error.game_finished": "Эта игра уже закончена.",833
"error.lobby_full": "Это лобби заполнено.",834
"error.unknown_code": "Лобби с таким кодом не найдено.",835
"error.cannot_vote": "Сейчас вы не можете голосовать.",836
"error.bad_vote": "Голосовать можно только за живого игрока.",837
"error.bad_give": "Столько очков действия отдать нельзя.",838
"error.unknown_action": "Неизвестное действие.",839
"error.ceasefire": "Во время перемирия атаковать нельзя.",840
"error.generic": "Что-то пошло не так. Попробуйте ещё раз.",841
"error.serverStatus": "Сервер вернул {status}.",842
}843
844
JA = {845
"app.name": NAME,846
"menu.tagline": "忍耐、同盟、そして時機を逃さない一撃のゲーム。",847
"menu.login": "ログイン",848
"menu.logout": "ログアウト",849
"menu.loggedInAs": "ログイン中",850
"menu.localTest": "ローカルテスト:",851
"menu.create": "新しいロビー",852
"menu.join": "参加",853
"menu.codePlaceholder": "コード",854
"menu.myGames": "あなたのゲーム",855
"menu.noGames": "まだゲームがありません。ロビーを作って他の人を招待しましょう。",856
"menu.authUnconfiguredHtml": "このサーバーではまだログインが設定されていません。コールバック <code>/allianties/callback.php</code> を auth.timfalken.com に登録し、クライアントシークレットを設定する必要があります。",857
"menu.guestHint": "ログインすると、ロビーの作成、招待、長く続くゲームの開始ができます。",858
"menu.open": "開く",859
"menu.continue": "続ける",860
"menu.statusLobby": "ロビー",861
"menu.statusRunning": "プレイ中",862
"menu.statusFinished": "終了",863
"menu.youWon": "勝利",864
"menu.draw": "引き分け",865
"menu.winnerIs": "勝者:{name}",866
"menu.needLogin": "プレイするには、まずログインしてください。",867
"menu.players": "プレイヤー",868
"lobby.title": "ロビー",869
"lobby.invite": "招待",870
"lobby.copy": "リンクをコピー",871
"lobby.copied": "コピーしました",872
"lobby.shareHint": "このコードまたはリンクを共有してください。プレイヤーはログインして参加します。",873
"lobby.players": "プレイヤー",874
"lobby.start": "ゲームを開始",875
"lobby.leave": "ロビーを退出",876
"lobby.host": "ホスト",877
"lobby.you": "あなた",878
"lobby.minPlayers": "開始するには少なくとも2人必要です。",879
"lobby.needTwo": "あと少なくとも1人を待っています…",880
"lobby.rules": "ルール",881
"lobby.jury": "陪審",882
"lobby.juryHint": "脱落したプレイヤーは毎日、生存中のプレイヤー1人に投票します。最多得票のプレイヤーは、次の毎日配布で行動力を1つ余分に受け取ります。同票の場合は、同票の全員がボーナスを受け取ります。投票は秘密で、配布まで変更できます。",883
"lobby.shrink": "縮小する戦場",884
"lobby.shrinkHint": "設定した日数ごとに、毎日の配布のときに外周が通行不能になります。その上にいるプレイヤーはライフを1失い、内側へ押し出されます。",885
"lobby.shrinkDays": "縮小の間隔(日)",886
"lobby.shrinkDaysHint": "最初の縮小はこの回数の深夜のあと、その後同じ日数ごとに繰り返し、戦場が最小サイズになるまで続きます。",887
"lobby.ceasefire": "強制停戦時間",888
"lobby.ceasefireHint": "この時間帯(Europe/Amsterdam)は誰も撃てません。移動、行動力の譲渡、射程の強化は可能です。時間帯は深夜をまたげます。",889
"lobby.ceasefireAdd": "時間帯を追加",890
"lobby.ceasefireRemove": "削除",891
"lobby.ceasefireStart": "開始",892
"lobby.ceasefireEnd": "終了",893
"lobby.ceasefireEmpty": "まだ時間帯がありません。追加するか、時計の上で扇形をドラッグしてください。",894
"lobby.ceasefireClock": "24時間時計。ハンドルをドラッグするか扇形を描きます。赤は停戦、金は攻撃可能。時刻は Europe/Amsterdam です。",895
"lobby.waiting": "ホストがゲームを開始するのを待っています。",896
"lobby.back": "戻る",897
"lobby.code": "コード",898
"lobby.playerCount.one": "{n}人のプレイヤー",899
"lobby.playerCount.other": "{n}人のプレイヤー",900
"lobby.playerCount.few": "{n}人のプレイヤー",901
"lobby.playerCount.many": "{n}人のプレイヤー",902
"game.day": "{n}日目",903
"game.nextAp": "次の行動力",904
"game.lives": "ライフ",905
"game.ap": "行動力",906
"game.range": "射程",907
"game.you": "あなた",908
"game.dead": "脱落",909
"game.surrendered": "降伏",910
"game.winner": "{name}の勝利!",911
"game.youWin": "あなたの勝利!",912
"game.draw": "引き分けでゲーム終了です。",913
"game.shrinkIn": "戦場は{n}日後に縮小します",914
"game.shrinkInDays.one": "戦場は{n}日後に縮小します",915
"game.shrinkInDays.other": "戦場は{n}日後に縮小します",916
"game.shrinkInDays.few": "戦場は{n}日後に縮小します",917
"game.shrinkInDays.many": "戦場は{n}日後に縮小します",918
"game.shrinkTomorrow": "戦場は明日縮小します",919
"game.shrinkToday": "戦場は次の配布時に縮小します",920
"game.upgrade": "射程を伸ばす",921
"game.settings": "設定",922
"game.surrender": "降伏する",923
"game.surrenderConfirm": "降伏しますか?このゲームから脱落します。取り消すことはできません。",924
"game.surrenderConfirmBtn": "はい、降伏する",925
"game.surrenderCancel": "キャンセル",926
"game.back": "メニューに戻る",927
"game.spectating": "あなたは脱落しました。観戦、メッセージ送信、陪審がオンなら投票はできます。",928
"game.ceasefireLeft": "停戦の残り時間",929
"game.ceasefireUntil": "停戦までの時間",930
"game.ceasefireActive": "停戦中",931
"game.attackDisabled": "攻撃",932
"game.attackDisabledReason": "停戦時間中は攻撃できません。",933
"game.selectSelf": "自分の戦車が選ばれています。ハイライトされたマスをタップして移動するか、射程を伸ばしてください。",934
"game.impassable": "通行不能",935
"game.willShrink": "次に縮小する輪",936
"opt.info": "情報",937
"opt.attack": "攻撃",938
"opt.give": "行動力を渡す",939
"opt.message": "メッセージを送る",940
"opt.close": "閉じる",941
"info.title": "情報",942
"info.lives": "ライフ",943
"info.ap": "行動力",944
"info.range": "射程",945
"info.notes": "非公開のメモ",946
"info.notesHint": "このメモはあなただけが見られます。アカウントに保存されます。",947
"info.saveNotes": "メモを保存",948
"info.saved": "保存しました",949
"give.title": "行動力を渡す",950
"give.howMany": "いくつ?",951
"give.send": "渡す",952
"give.youHave": "あなたは{n}持っています。",953
"chat.title": "{name}へのメッセージ",954
"chat.placeholder": "非公開メッセージを書く…",955
"chat.send": "送信",956
"chat.empty": "まだメッセージはありません。",957
"jury.title": "陪審",958
"jury.hint": "生存中のプレイヤー1人に投票します。最多得票者は次の配布で行動力を1つ余分に得ます。それまで投票は変更できます。他のプレイヤーに投票は見えません。",959
"jury.vote": "投票する",960
"jury.votedFor": "{name}に投票しました",961
"jury.change": "投票を変更",962
"timeline.play": "再生",963
"timeline.pause": "一時停止",964
"timeline.live": "ライブ",965
"timeline.event.start": "ゲーム開始",966
"timeline.event.move": "{name}が移動",967
"timeline.event.shoot": "{name}が{target}を撃つ",968
"timeline.event.give": "{name}が{target}に行動力を{n}渡す",969
"timeline.event.upgrade": "{name}が射程を{n}に伸ばす",970
"timeline.event.surrender": "{name}が降伏",971
"timeline.event.daily": "{n}日目:行動力の配布",972
"timeline.event.jury": "陪審が{name}にボーナスを与える",973
"timeline.event.juryTie": "陪審が{names}にボーナスを与える",974
"timeline.event.shrink": "戦場が縮小する",975
"timeline.event.win": "{name}の勝利",976
"timeline.event.death": "{name}が脱落",977
"timeline.event.deathShot": "{name}が{by}に撃たれて脱落",978
"timeline.event.deathShrink": "{name}が縮小する戦場に巻き込まれた",979
"timeline.event.deathCrushed": "{name}は押しつぶされた:空きマスがない",980
"timeline.event.draw": "引き分けで終了",981
"auth.unavailable": "ログインは一時的に利用できません。",982
"auth.backToGame": "Alliantiesに戻る",983
"auth.failed": "ログインに失敗しました。",984
"auth.retry": "再試行",985
"auth.back": "戻る",986
"lang.choose": "言語を選択",987
"lang.current": "言語:{name}",988
"error.login": "続けるにはログインしてください。",989
"error.csrf": "セッションの期限が切れました。ページを更新してもう一度お試しください。",990
"error.not_host": "ホストだけがそれを行えます。",991
"error.min_players": "開始するには少なくとも2人必要です。",992
"error.not_in_game": "このゲームには参加していません。",993
"error.dead": "このゲームから脱落しています。",994
"error.no_ap": "行動力が残っていません。",995
"error.occupied": "そのマスは占有されています。",996
"error.impassable": "そのマスは通行不能です。",997
"error.out_of_range": "そのプレイヤーは射程外です。",998
"error.invalid_move": "その行動はできません。",999
"error.game_started": "このゲームはすでに始まっています。",1000
"error.game_finished": "このゲームは終了しています。",1001
"error.lobby_full": "このロビーは満員です。",1002
"error.unknown_code": "そのコードのロビーは見つかりません。",1003
"error.cannot_vote": "今は投票できません。",1004
"error.bad_vote": "生存中のプレイヤーにしか投票できません。",1005
"error.bad_give": "そんなに多くの行動力は渡せません。",1006
"error.unknown_action": "不明な行動です。",1007
"error.ceasefire": "停戦時間中は攻撃できません。",1008
"error.generic": "問題が発生しました。もう一度お試しください。",1009
"error.serverStatus": "サーバーは{status}を返しました。",1010
}1011
1012
ZH = {1013
"app.name": NAME,1014
"menu.tagline": "一场关于耐心、同盟与精准开火的游戏。",1015
"menu.login": "登录",1016
"menu.logout": "退出登录",1017
"menu.loggedInAs": "已登录为",1018
"menu.localTest": "本地测试:",1019
"menu.create": "新建大厅",1020
"menu.join": "加入",1021
"menu.codePlaceholder": "代码",1022
"menu.myGames": "你的对局",1023
"menu.noGames": "你还没有任何对局。新建一个大厅并邀请其他人吧。",1024
"menu.authUnconfiguredHtml": "此服务器尚未设置登录。需要在 auth.timfalken.com 上注册回调 <code>/allianties/callback.php</code>,并配置客户端密钥。",1025
"menu.guestHint": "登录后可以创建大厅、邀请玩家并开始一局长时间进行的游戏。",1026
"menu.open": "打开",1027
"menu.continue": "继续",1028
"menu.statusLobby": "大厅",1029
"menu.statusRunning": "进行中",1030
"menu.statusFinished": "已结束",1031
"menu.youWon": "你赢了",1032
"menu.draw": "平局",1033
"menu.winnerIs": "胜者:{name}",1034
"menu.needLogin": "请先登录再游戏。",1035
"menu.players": "玩家",1036
"lobby.title": "大厅",1037
"lobby.invite": "邀请",1038
"lobby.copy": "复制链接",1039
"lobby.copied": "已复制",1040
"lobby.shareHint": "分享此代码或链接。玩家登录后即可加入。",1041
"lobby.players": "玩家",1042
"lobby.start": "开始游戏",1043
"lobby.leave": "离开大厅",1044
"lobby.host": "房主",1045
"lobby.you": "你",1046
"lobby.minPlayers": "至少需要两名玩家才能开始。",1047
"lobby.needTwo": "正在等待至少再来一名玩家…",1048
"lobby.rules": "规则",1049
"lobby.jury": "陪审团",1050
"lobby.juryHint": "被淘汰的玩家每天为一名仍存活的玩家投票。得票最多的玩家在下一次每日发放时额外获得 1 点行动点。若并列,所有并列者都获得奖励。投票对他人保密,并可在发放前更改。",1051
"lobby.shrink": "缩小的战场",1052
"lobby.shrinkHint": "每隔设定的天数,在每日发放时外圈会变为不可通行。站在上面的玩家失去 1 点生命并被推向内侧。",1053
"lobby.shrinkDays": "两次缩小间隔天数",1054
"lobby.shrinkDaysHint": "第一次缩小发生在这么多个午夜之后,之后每隔同样天数再缩小,直到战场达到最小尺寸。",1055
"lobby.ceasefire": "强制停火时段",1056
"lobby.ceasefireHint": "在这些时段(Europe/Amsterdam)任何人不得射击。移动、给予行动点和提升射程仍然允许。时段可以跨越午夜。",1057
"lobby.ceasefireAdd": "添加时段",1058
"lobby.ceasefireRemove": "删除",1059
"lobby.ceasefireStart": "从",1060
"lobby.ceasefireEnd": "至",1061
"lobby.ceasefireEmpty": "还没有时段。请添加一个,或在时钟上拖出一段扇形。",1062
"lobby.ceasefireClock": "24 小时时钟。拖动手柄或画出扇形;红色为停火,金色为可开火。时间为 Europe/Amsterdam。",1063
"lobby.waiting": "等待房主开始游戏。",1064
"lobby.back": "返回",1065
"lobby.code": "代码",1066
"lobby.playerCount.one": "{n} 名玩家",1067
"lobby.playerCount.other": "{n} 名玩家",1068
"lobby.playerCount.few": "{n} 名玩家",1069
"lobby.playerCount.many": "{n} 名玩家",1070
"game.day": "第 {n} 天",1071
"game.nextAp": "下次行动点",1072
"game.lives": "生命",1073
"game.ap": "行动点",1074
"game.range": "射程",1075
"game.you": "你",1076
"game.dead": "已淘汰",1077
"game.surrendered": "已投降",1078
"game.winner": "{name} 获胜!",1079
"game.youWin": "你赢了!",1080
"game.draw": "本局以平局结束。",1081
"game.shrinkIn": "战场将在 {n} 天后缩小",1082
"game.shrinkInDays.one": "战场将在 {n} 天后缩小",1083
"game.shrinkInDays.other": "战场将在 {n} 天后缩小",1084
"game.shrinkInDays.few": "战场将在 {n} 天后缩小",1085
"game.shrinkInDays.many": "战场将在 {n} 天后缩小",1086
"game.shrinkTomorrow": "战场将在明天缩小",1087
"game.shrinkToday": "战场将在下次发放时缩小",1088
"game.upgrade": "提升射程",1089
"game.settings": "设置",1090
"game.surrender": "投降",1091
"game.surrenderConfirm": "确定投降?你将退出本局,且无法撤销。",1092
"game.surrenderConfirmBtn": "是的,投降",1093
"game.surrenderCancel": "取消",1094
"game.back": "返回菜单",1095
"game.spectating": "你已被淘汰。你仍可观战、发送消息,并在陪审团开启时投票。",1096
"game.ceasefireLeft": "停火剩余时间",1097
"game.ceasefireUntil": "距离停火",1098
"game.ceasefireActive": "停火中",1099
"game.attackDisabled": "攻击",1100
"game.attackDisabledReason": "停火时段内不得攻击。",1101
"game.selectSelf": "已选中你的坦克。点按高亮格子移动,或提升射程。",1102
"game.impassable": "不可通行",1103
"game.willShrink": "下一圈将缩小",1104
"opt.info": "信息",1105
"opt.attack": "攻击",1106
"opt.give": "给予行动点",1107
"opt.message": "发送消息",1108
"opt.close": "关闭",1109
"info.title": "信息",1110
"info.lives": "生命",1111
"info.ap": "行动点",1112
"info.range": "射程",1113
"info.notes": "你的私人备注",1114
"info.notesHint": "只有你能看到这些备注。它们保存在你的账户中。",1115
"info.saveNotes": "保存备注",1116
"info.saved": "已保存",1117
"give.title": "给予行动点",1118
"give.howMany": "给多少?",1119
"give.send": "给予",1120
"give.youHave": "你有 {n} 点。",1121
"chat.title": "给 {name} 的消息",1122
"chat.placeholder": "写一条私人消息…",1123
"chat.send": "发送",1124
"chat.empty": "还没有消息。",1125
"jury.title": "陪审团",1126
"jury.hint": "为一名仍存活的玩家投票。得票最多者在下次发放时额外获得 1 点行动点。在此之前可以改票。其他玩家看不到你的投票。",1127
"jury.vote": "投票",1128
"jury.votedFor": "你把票投给了 {name}",1129
"jury.change": "改票",1130
"timeline.play": "播放",1131
"timeline.pause": "暂停",1132
"timeline.live": "实时",1133
"timeline.event.start": "游戏开始",1134
"timeline.event.move": "{name} 移动了",1135
"timeline.event.shoot": "{name} 向 {target} 射击",1136
"timeline.event.give": "{name} 将 {n} 点行动点给了 {target}",1137
"timeline.event.upgrade": "{name} 将射程提升到 {n}",1138
"timeline.event.surrender": "{name} 投降了",1139
"timeline.event.daily": "第 {n} 天:发放行动点",1140
"timeline.event.jury": "陪审团将奖励发给 {name}",1141
"timeline.event.juryTie": "陪审团将奖励发给 {names}",1142
"timeline.event.shrink": "战场缩小了",1143
"timeline.event.win": "{name} 获胜",1144
"timeline.event.death": "{name} 被淘汰",1145
"timeline.event.deathShot": "{name} 被 {by} 击倒",1146
"timeline.event.deathShrink": "{name} 被缩小的战场波及",1147
"timeline.event.deathCrushed": "{name} 被挤出:没有空余格子",1148
"timeline.event.draw": "本局以平局结束",1149
"auth.unavailable": "登录暂时不可用。",1150
"auth.backToGame": "返回 Allianties",1151
"auth.failed": "登录失败。",1152
"auth.retry": "重试",1153
"auth.back": "返回",1154
"lang.choose": "选择语言",1155
"lang.current": "语言:{name}",1156
"error.login": "请登录后再继续。",1157
"error.csrf": "会话已过期。请刷新页面后再试。",1158
"error.not_host": "只有房主可以这样做。",1159
"error.min_players": "至少需要两名玩家才能开始。",1160
"error.not_in_game": "你不在这局游戏中。",1161
"error.dead": "你已从本局淘汰。",1162
"error.no_ap": "你没有剩余的行动点。",1163
"error.occupied": "该格子已被占用。",1164
"error.impassable": "该格子不可通行。",1165
"error.out_of_range": "该玩家超出射程。",1166
"error.invalid_move": "不允许这样行动。",1167
"error.game_started": "这局游戏已经开始。",1168
"error.game_finished": "这局游戏已经结束。",1169
"error.lobby_full": "此大厅已满。",1170
"error.unknown_code": "找不到该代码对应的大厅。",1171
"error.cannot_vote": "你现在不能投票。",1172
"error.bad_vote": "只能为仍存活的玩家投票。",1173
"error.bad_give": "不能给予那么多行动点。",1174
"error.unknown_action": "未知操作。",1175
"error.ceasefire": "停火时段内不能攻击。",1176
"error.generic": "出了点问题,请再试一次。",1177
"error.serverStatus": "服务器返回了 {status}。",1178
}1179
1180
KO = {1181
"app.name": NAME,1182
"menu.tagline": "인내와 동맹, 그리고 때를 놓치지 않는 사격의 게임.",1183
"menu.login": "로그인",1184
"menu.logout": "로그아웃",1185
"menu.loggedInAs": "로그인됨",1186
"menu.localTest": "로컬 테스트:",1187
"menu.create": "새 로비",1188
"menu.join": "참가",1189
"menu.codePlaceholder": "코드",1190
"menu.myGames": "내 게임",1191
"menu.noGames": "아직 게임이 없습니다. 로비를 만들고 다른 사람을 초대하세요.",1192
"menu.authUnconfiguredHtml": "이 서버에는 아직 로그인이 설정되지 않았습니다. 콜백 <code>/allianties/callback.php</code>를 auth.timfalken.com에 등록하고 클라이언트 비밀키를 설정해야 합니다.",1193
"menu.guestHint": "로그인하면 로비를 만들고, 플레이어를 초대하고, 오래 이어지는 게임을 시작할 수 있습니다.",1194
"menu.open": "열기",1195
"menu.continue": "계속",1196
"menu.statusLobby": "로비",1197
"menu.statusRunning": "진행 중",1198
"menu.statusFinished": "종료",1199
"menu.youWon": "승리",1200
"menu.draw": "무승부",1201
"menu.winnerIs": "승자: {name}",1202
"menu.needLogin": "플레이하려면 먼저 로그인하세요.",1203
"menu.players": "플레이어",1204
"lobby.title": "로비",1205
"lobby.invite": "초대",1206
"lobby.copy": "링크 복사",1207
"lobby.copied": "복사됨",1208
"lobby.shareHint": "이 코드나 링크를 공유하세요. 플레이어는 로그인한 뒤 참가합니다.",1209
"lobby.players": "플레이어",1210
"lobby.start": "게임 시작",1211
"lobby.leave": "로비 나가기",1212
"lobby.host": "호스트",1213
"lobby.you": "나",1214
"lobby.minPlayers": "시작하려면 플레이어가 최소 두 명 필요합니다.",1215
"lobby.needTwo": "플레이어를 최소 한 명 더 기다리는 중…",1216
"lobby.rules": "규칙",1217
"lobby.jury": "배심",1218
"lobby.juryHint": "탈락한 플레이어는 매일 생존 중인 플레이어 한 명에게 투표합니다. 가장 많은 표를 받은 플레이어는 다음 일일 지급 때 행동력을 하나 더 받습니다. 동점이면 동점인 전원에게 보너스가 갑니다. 표는 비밀이며 지급 전까지 바꿀 수 있습니다.",1219
"lobby.shrink": "줄어드는 전장",1220
"lobby.shrinkHint": "설정한 일수가 지나면 일일 지급 때 바깥 고리가 통과 불가가 됩니다. 그 위에 있는 플레이어는 목숨을 하나 잃고 안쪽으로 밀립니다.",1221
"lobby.shrinkDays": "축소 간격(일)",1222
"lobby.shrinkDaysHint": "첫 축소는 그 횟수만큼의 자정이 지난 뒤, 이후 같은 일수마다 반복되며 전장이 최소 크기에 이를 때까지 계속됩니다.",1223
"lobby.ceasefire": "강제 휴전 시간",1224
"lobby.ceasefireHint": "이 시간대(Europe/Amsterdam)에는 아무도 발사할 수 없습니다. 이동, 행동력 전달, 사거리 강화는 가능합니다. 구간은 자정을 넘길 수 있습니다.",1225
"lobby.ceasefireAdd": "구간 추가",1226
"lobby.ceasefireRemove": "삭제",1227
"lobby.ceasefireStart": "시작",1228
"lobby.ceasefireEnd": "종료",1229
"lobby.ceasefireEmpty": "아직 구간이 없습니다. 하나를 추가하거나 시계에서 부채꼴을 드래그하세요.",1230
"lobby.ceasefireClock": "24시간 시계. 핸들을 드래그하거나 부채꼴을 그리세요. 빨강은 휴전, 금색은 사격 가능. 시각은 Europe/Amsterdam입니다.",1231
"lobby.waiting": "호스트가 게임을 시작하기를 기다리는 중.",1232
"lobby.back": "뒤로",1233
"lobby.code": "코드",1234
"lobby.playerCount.one": "플레이어 {n}명",1235
"lobby.playerCount.other": "플레이어 {n}명",1236
"lobby.playerCount.few": "플레이어 {n}명",1237
"lobby.playerCount.many": "플레이어 {n}명",1238
"game.day": "{n}일차",1239
"game.nextAp": "다음 행동력",1240
"game.lives": "목숨",1241
"game.ap": "행동력",1242
"game.range": "사거리",1243
"game.you": "나",1244
"game.dead": "탈락",1245
"game.surrendered": "항복함",1246
"game.winner": "{name} 승리!",1247
"game.youWin": "당신이 이겼습니다!",1248
"game.draw": "게임이 무승부로 끝났습니다.",1249
"game.shrinkIn": "전장이 {n}일 후 줄어듭니다",1250
"game.shrinkInDays.one": "전장이 {n}일 후 줄어듭니다",1251
"game.shrinkInDays.other": "전장이 {n}일 후 줄어듭니다",1252
"game.shrinkInDays.few": "전장이 {n}일 후 줄어듭니다",1253
"game.shrinkInDays.many": "전장이 {n}일 후 줄어듭니다",1254
"game.shrinkTomorrow": "전장이 내일 줄어듭니다",1255
"game.shrinkToday": "전장이 다음 지급 때 줄어듭니다",1256
"game.upgrade": "사거리 강화",1257
"game.settings": "설정",1258
"game.surrender": "항복",1259
"game.surrenderConfirm": "항복할까요? 이 게임에서 탈락하며 되돌릴 수 없습니다.",1260
"game.surrenderConfirmBtn": "네, 항복합니다",1261
"game.surrenderCancel": "취소",1262
"game.back": "메뉴로 돌아가기",1263
"game.spectating": "탈락했습니다. 관전, 메시지 보내기, 배심이 켜져 있다면 투표는 계속할 수 있습니다.",1264
"game.ceasefireLeft": "휴전 남은 시간",1265
"game.ceasefireUntil": "휴전까지",1266
"game.ceasefireActive": "휴전 중",1267
"game.attackDisabled": "공격",1268
"game.attackDisabledReason": "휴전 시간에는 공격할 수 없습니다.",1269
"game.selectSelf": "내 전차가 선택되었습니다. 강조된 칸을 눌러 이동하거나 사거리를 강화하세요.",1270
"game.impassable": "통과 불가",1271
"game.willShrink": "다음에 줄어들 고리",1272
"opt.info": "정보",1273
"opt.attack": "공격",1274
"opt.give": "행동력 주기",1275
"opt.message": "메시지 보내기",1276
"opt.close": "닫기",1277
"info.title": "정보",1278
"info.lives": "목숨",1279
"info.ap": "행동력",1280
"info.range": "사거리",1281
"info.notes": "나만 보는 메모",1282
"info.notesHint": "이 메모는 당신만 볼 수 있습니다. 계정에 저장됩니다.",1283
"info.saveNotes": "메모 저장",1284
"info.saved": "저장됨",1285
"give.title": "행동력 주기",1286
"give.howMany": "몇 개?",1287
"give.send": "주기",1288
"give.youHave": "{n}개를 가지고 있습니다.",1289
"chat.title": "{name}에게 메시지",1290
"chat.placeholder": "비공개 메시지를 작성하세요…",1291
"chat.send": "보내기",1292
"chat.empty": "아직 메시지가 없습니다.",1293
"jury.title": "배심",1294
"jury.hint": "생존 중인 플레이어 한 명에게 투표하세요. 가장 많은 표를 받은 사람은 다음 지급 때 행동력을 하나 더 받습니다. 그 전까지 표를 바꿀 수 있습니다. 다른 플레이어는 당신의 표를 볼 수 없습니다.",1295
"jury.vote": "투표",1296
"jury.votedFor": "{name}에게 투표했습니다",1297
"jury.change": "투표 변경",1298
"timeline.play": "재생",1299
"timeline.pause": "일시정지",1300
"timeline.live": "실시간",1301
"timeline.event.start": "게임이 시작됩니다",1302
"timeline.event.move": "{name}이(가) 이동합니다",1303
"timeline.event.shoot": "{name}이(가) {target}을(를) 공격합니다",1304
"timeline.event.give": "{name}이(가) {target}에게 행동력 {n}개를 줍니다",1305
"timeline.event.upgrade": "{name}이(가) 사거리를 {n}(으)로 올립니다",1306
"timeline.event.surrender": "{name}이(가) 항복합니다",1307
"timeline.event.daily": "{n}일차: 행동력 지급",1308
"timeline.event.jury": "배심이 {name}에게 보너스를 줍니다",1309
"timeline.event.juryTie": "배심이 {names}에게 보너스를 줍니다",1310
"timeline.event.shrink": "전장이 줄어듭니다",1311
"timeline.event.win": "{name} 승리",1312
"timeline.event.death": "{name} 탈락",1313
"timeline.event.deathShot": "{name}이(가) {by}에게 피격되어 탈락",1314
"timeline.event.deathShrink": "{name}이(가) 줄어드는 전장에 걸렸습니다",1315
"timeline.event.deathCrushed": "{name}이(가) 깔렸습니다: 빈 칸이 없습니다",1316
"timeline.event.draw": "게임이 무승부로 끝납니다",1317
"auth.unavailable": "로그인을 잠시 사용할 수 없습니다.",1318
"auth.backToGame": "Allianties로 돌아가기",1319
"auth.failed": "로그인에 실패했습니다.",1320
"auth.retry": "다시 시도",1321
"auth.back": "뒤로",1322
"lang.choose": "언어 선택",1323
"lang.current": "언어: {name}",1324
"error.login": "계속하려면 로그인하세요.",1325
"error.csrf": "세션이 만료되었습니다. 페이지를 새로 고친 뒤 다시 시도하세요.",1326
"error.not_host": "호스트만 할 수 있습니다.",1327
"error.min_players": "시작하려면 플레이어가 최소 두 명 필요합니다.",1328
"error.not_in_game": "이 게임에 들어가 있지 않습니다.",1329
"error.dead": "이 게임에서 탈락했습니다.",1330
"error.no_ap": "남은 행동력이 없습니다.",1331
"error.occupied": "그 칸은 이미 차지되어 있습니다.",1332
"error.impassable": "그 칸은 통과할 수 없습니다.",1333
"error.out_of_range": "그 플레이어는 사거리 밖입니다.",1334
"error.invalid_move": "그 행동은 허용되지 않습니다.",1335
"error.game_started": "이 게임은 이미 시작되었습니다.",1336
"error.game_finished": "이 게임은 이미 끝났습니다.",1337
"error.lobby_full": "이 로비는 가득 찼습니다.",1338
"error.unknown_code": "그 코드의 로비를 찾을 수 없습니다.",1339
"error.cannot_vote": "지금은 투표할 수 없습니다.",1340
"error.bad_vote": "생존 중인 플레이어에게만 투표할 수 있습니다.",1341
"error.bad_give": "그만큼의 행동력은 줄 수 없습니다.",1342
"error.unknown_action": "알 수 없는 행동입니다.",1343
"error.ceasefire": "휴전 시간에는 공격할 수 없습니다.",1344
"error.generic": "문제가 발생했습니다. 다시 시도해 주세요.",1345
"error.serverStatus": "서버가 {status}을(를) 반환했습니다.",1346
}@@ -0,0 +1,17 @@
1
Options -Indexes
2
DirectoryIndex index.html index.php
3
4
<FilesMatch "^(router\.php|README\.md)$">
5
Require all denied
6
</FilesMatch>
7
8
<IfModule mod_headers.c>
9
Header always set X-Content-Type-Options "nosniff"
10
Header always set Referrer-Policy "same-origin"
11
</IfModule>
12
13
<IfModule mod_headers.c>
14
<FilesMatch "\.(php)$">
15
Header set Cache-Control "no-store"
16
</FilesMatch>
17
</IfModule>
@@ -0,0 +1,17 @@1
Options -Indexes2
DirectoryIndex index.html index.php3
4
<FilesMatch "^(router\.php|README\.md)$">5
Require all denied6
</FilesMatch>7
8
<IfModule mod_headers.c>9
Header always set X-Content-Type-Options "nosniff"10
Header always set Referrer-Policy "same-origin"11
</IfModule>12
13
<IfModule mod_headers.c>14
<FilesMatch "\.(php)$">15
Header set Cache-Control "no-store"16
</FilesMatch>17
</IfModule>@@ -0,0 +1,188 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
require __DIR__ . '/lib/Store.php';
5
6
$action = $_GET['action'] ?? $_POST['action'] ?? '';
7
if ($action === '') {
8
$body = readJsonBody();
9
$action = (string) ($body['action'] ?? '');
10
} else {
11
$body = readJsonBody();
12
}
13
14
try {
15
$configured = authConfigured();
16
$local = localDev();
17
$user = currentUser();
18
19
if ($action === 'me' || $action === '') {
20
$games = [];
21
$locale = null;
22
if ($user) {
23
$store = Store::open();
24
$games = $store->listFor($user['id']);
25
$locale = $store->locale($user['id']);
26
}
27
jsonOut([
28
'ok' => true,
29
'configured' => $configured,
30
'local' => $local,
31
'csrf' => csrfToken(),
32
'me' => $user,
33
'games' => $games,
34
'locale' => $locale,
35
'login_url' => 'auth.php',
36
'logout_url' => 'logout.php',
37
'timezone' => Engine::TZ,
38
'defaults' => Engine::defaultRules(),
39
'server_now' => Engine::now(),
40
]);
41
}
42
43
if ($action === 'test_login') {
44
if (!localDev()) {
45
jsonFail('generic', 403);
46
}
47
requireCsrf();
48
$who = (string) ($body['user'] ?? $_GET['user'] ?? '');
49
if (!preg_match('/^test_user_([1-9]|1[0-6])$/', $who)) {
50
jsonFail('generic');
51
}
52
loginUser('local:' . $who, $who, 'images/avatars/' . $who . '.svg');
53
jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);
54
}
55
56
if (!$user && $action !== 'me') {
57
jsonFail('login', 401);
58
}
59
60
requireCsrf();
61
$store = Store::open();
62
$userId = $user['id'];
63
$name = $user['name'];
64
$avatar = $user['avatar'] ?? null;
65
66
$gameId = (string) ($body['game'] ?? $body['game_id'] ?? $_GET['game'] ?? '');
67
68
switch ($action) {
69
case 'set_locale':
70
$locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
71
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);
72
73
case 'lobby_create':
74
$rules = is_array($body['rules'] ?? null) ? $body['rules'] : $body;
75
$game = $store->createLobby($userId, $name, $avatar, $rules);
76
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
77
78
case 'lobby_join':
79
$code = (string) ($body['code'] ?? $_GET['code'] ?? '');
80
$game = $store->joinByCode($userId, $name, $avatar, $code);
81
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
82
83
case 'lobby_leave':
84
if ($gameId === '') {
85
jsonFail('unknown_code');
86
}
87
$game = $store->leaveLobby($userId, $gameId);
88
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $game ? $store->view($game, $userId) : null]);
89
90
case 'lobby_rules':
91
if ($gameId === '') {
92
jsonFail('unknown_code');
93
}
94
$rules = is_array($body['rules'] ?? null) ? $body['rules'] : $body;
95
$game = $store->setRules($userId, $gameId, $rules);
96
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
97
98
case 'lobby_start':
99
if ($gameId === '') {
100
jsonFail('unknown_code');
101
}
102
$game = $store->startGame($userId, $gameId);
103
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
104
105
case 'act':
106
case 'game_action':
107
if ($gameId === '') {
108
jsonFail('unknown_code');
109
}
110
$actionBody = is_array($body['move'] ?? null) ? $body['move'] : $body;
111
// Don't pass internal keys as the action.
112
unset($actionBody['action'], $actionBody['game'], $actionBody['game_id'], $actionBody['csrf']);
113
$game = $store->act($userId, $gameId, $actionBody);
114
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
115
116
case 'note':
117
if ($gameId === '') {
118
jsonFail('unknown_code');
119
}
120
$game = $store->setNote(
121
$userId,
122
$gameId,
123
(string) ($body['subject'] ?? $body['target'] ?? ''),
124
(string) ($body['text'] ?? $body['note'] ?? '')
125
);
126
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
127
128
case 'message':
129
case 'chat':
130
if ($gameId === '') {
131
jsonFail('unknown_code');
132
}
133
$game = $store->addMessage(
134
$userId,
135
$gameId,
136
(string) ($body['to'] ?? $body['target'] ?? ''),
137
(string) ($body['text'] ?? $body['message'] ?? '')
138
);
139
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
140
141
case 'sync':
142
if ($gameId === '') {
143
jsonFail('unknown_code');
144
}
145
$since = (int) ($body['v'] ?? $body['version'] ?? $_GET['v'] ?? $_GET['version'] ?? -1);
146
$payload = $store->sync($userId, $gameId, $since);
147
$payload['csrf'] = csrfToken();
148
jsonOut($payload);
149
150
case 'game':
151
case 'poll':
152
if ($gameId === '') {
153
jsonFail('unknown_code');
154
}
155
$view = $store->present($userId, $gameId);
156
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $view]);
157
158
case 'games':
159
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'games' => $store->listFor($userId)]);
160
161
case 'debug_advance':
162
if (!localDev()) {
163
jsonFail('generic', 403);
164
}
165
if ($gameId === '') {
166
jsonFail('unknown_code');
167
}
168
$days = isset($body['days']) ? (int) $body['days'] : 1;
169
$at = isset($body['at']) ? (int) $body['at'] : Engine::now();
170
$game = $store->debugAdvance($userId, $gameId, $at, $days);
171
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);
172
173
default:
174
jsonFail('unknown_action');
175
}
176
} catch (RuntimeException $e) {
177
$code = $e->getMessage();
178
$http = 400;
179
if (in_array($code, ['login', 'not_in_game'], true)) {
180
$http = $code === 'login' ? 401 : 403;
181
}
182
if (in_array($code, ['csrf'], true)) {
183
$http = 403;
184
}
185
jsonFail($code, $http);
186
} catch (Throwable $e) {
187
jsonFail('generic', 500);
188
}
@@ -0,0 +1,188 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
require __DIR__ . '/lib/Store.php';5
6
$action = $_GET['action'] ?? $_POST['action'] ?? '';7
if ($action === '') {8
$body = readJsonBody();9
$action = (string) ($body['action'] ?? '');10
} else {11
$body = readJsonBody();12
}13
14
try {15
$configured = authConfigured();16
$local = localDev();17
$user = currentUser();18
19
if ($action === 'me' || $action === '') {20
$games = [];21
$locale = null;22
if ($user) {23
$store = Store::open();24
$games = $store->listFor($user['id']);25
$locale = $store->locale($user['id']);26
}27
jsonOut([28
'ok' => true,29
'configured' => $configured,30
'local' => $local,31
'csrf' => csrfToken(),32
'me' => $user,33
'games' => $games,34
'locale' => $locale,35
'login_url' => 'auth.php',36
'logout_url' => 'logout.php',37
'timezone' => Engine::TZ,38
'defaults' => Engine::defaultRules(),39
'server_now' => Engine::now(),40
]);41
}42
43
if ($action === 'test_login') {44
if (!localDev()) {45
jsonFail('generic', 403);46
}47
requireCsrf();48
$who = (string) ($body['user'] ?? $_GET['user'] ?? '');49
if (!preg_match('/^test_user_([1-9]|1[0-6])$/', $who)) {50
jsonFail('generic');51
}52
loginUser('local:' . $who, $who, 'images/avatars/' . $who . '.svg');53
jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);54
}55
56
if (!$user && $action !== 'me') {57
jsonFail('login', 401);58
}59
60
requireCsrf();61
$store = Store::open();62
$userId = $user['id'];63
$name = $user['name'];64
$avatar = $user['avatar'] ?? null;65
66
$gameId = (string) ($body['game'] ?? $body['game_id'] ?? $_GET['game'] ?? '');67
68
switch ($action) {69
case 'set_locale':70
$locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));71
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);72
73
case 'lobby_create':74
$rules = is_array($body['rules'] ?? null) ? $body['rules'] : $body;75
$game = $store->createLobby($userId, $name, $avatar, $rules);76
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);77
78
case 'lobby_join':79
$code = (string) ($body['code'] ?? $_GET['code'] ?? '');80
$game = $store->joinByCode($userId, $name, $avatar, $code);81
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);82
83
case 'lobby_leave':84
if ($gameId === '') {85
jsonFail('unknown_code');86
}87
$game = $store->leaveLobby($userId, $gameId);88
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $game ? $store->view($game, $userId) : null]);89
90
case 'lobby_rules':91
if ($gameId === '') {92
jsonFail('unknown_code');93
}94
$rules = is_array($body['rules'] ?? null) ? $body['rules'] : $body;95
$game = $store->setRules($userId, $gameId, $rules);96
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);97
98
case 'lobby_start':99
if ($gameId === '') {100
jsonFail('unknown_code');101
}102
$game = $store->startGame($userId, $gameId);103
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);104
105
case 'act':106
case 'game_action':107
if ($gameId === '') {108
jsonFail('unknown_code');109
}110
$actionBody = is_array($body['move'] ?? null) ? $body['move'] : $body;111
// Don't pass internal keys as the action.112
unset($actionBody['action'], $actionBody['game'], $actionBody['game_id'], $actionBody['csrf']);113
$game = $store->act($userId, $gameId, $actionBody);114
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);115
116
case 'note':117
if ($gameId === '') {118
jsonFail('unknown_code');119
}120
$game = $store->setNote(121
$userId,122
$gameId,123
(string) ($body['subject'] ?? $body['target'] ?? ''),124
(string) ($body['text'] ?? $body['note'] ?? '')125
);126
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);127
128
case 'message':129
case 'chat':130
if ($gameId === '') {131
jsonFail('unknown_code');132
}133
$game = $store->addMessage(134
$userId,135
$gameId,136
(string) ($body['to'] ?? $body['target'] ?? ''),137
(string) ($body['text'] ?? $body['message'] ?? '')138
);139
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);140
141
case 'sync':142
if ($gameId === '') {143
jsonFail('unknown_code');144
}145
$since = (int) ($body['v'] ?? $body['version'] ?? $_GET['v'] ?? $_GET['version'] ?? -1);146
$payload = $store->sync($userId, $gameId, $since);147
$payload['csrf'] = csrfToken();148
jsonOut($payload);149
150
case 'game':151
case 'poll':152
if ($gameId === '') {153
jsonFail('unknown_code');154
}155
$view = $store->present($userId, $gameId);156
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $view]);157
158
case 'games':159
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'games' => $store->listFor($userId)]);160
161
case 'debug_advance':162
if (!localDev()) {163
jsonFail('generic', 403);164
}165
if ($gameId === '') {166
jsonFail('unknown_code');167
}168
$days = isset($body['days']) ? (int) $body['days'] : 1;169
$at = isset($body['at']) ? (int) $body['at'] : Engine::now();170
$game = $store->debugAdvance($userId, $gameId, $at, $days);171
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'game' => $store->view($game, $userId)]);172
173
default:174
jsonFail('unknown_action');175
}176
} catch (RuntimeException $e) {177
$code = $e->getMessage();178
$http = 400;179
if (in_array($code, ['login', 'not_in_game'], true)) {180
$http = $code === 'login' ? 401 : 403;181
}182
if (in_array($code, ['csrf'], true)) {183
$http = 403;184
}185
jsonFail($code, $http);186
} catch (Throwable $e) {187
jsonFail('generic', 500);188
}@@ -0,0 +1,43 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
require __DIR__ . '/lib/I18n.php';
5
6
try {
7
$next = safeNext($_GET['next'] ?? null);
8
if ($next) {
9
$_SESSION['after_login'] = $next;
10
}
11
if (localDev() && isset($_GET['test'])) {
12
$n = (int) $_GET['test'];
13
if ($n < 1 || $n > ALLIANTIES_TEST_USERS) {
14
throw new RuntimeException('Onbekende testgebruiker.');
15
}
16
$who = 'test_user_' . $n;
17
loginUser('local:' . $who, $who, 'images/avatars/' . $who . '.svg');
18
$dest = $_SESSION['after_login'] ?? (is_string($next) ? $next : 'index.html');
19
unset($_SESSION['after_login']);
20
header('Location: ' . $dest);
21
exit;
22
}
23
if (!authConfigured()) {
24
header('Location: index.html?auth=unconfigured');
25
exit;
26
}
27
$cfg = config();
28
$_SESSION['oauth_state'] = bin2hex(random_bytes(32));
29
$_SESSION['oauth_started'] = time();
30
header('Location: ' . authUrl() . '/oauth/authorize?' . http_build_query([
31
'client_id' => $cfg['client_id'],
32
'redirect_uri' => baseUrl() . '/callback.php',
33
'response_type' => 'code',
34
'state' => $_SESSION['oauth_state'],
35
]));
36
} catch (Throwable $e) {
37
http_response_code(503);
38
header('Content-Type: text/html; charset=utf-8');
39
$lang = I18n::htmlLang();
40
echo '<!DOCTYPE html><html lang="' . htmlspecialchars($lang) . '"><meta charset="utf-8"><title>Allianties</title>';
41
echo '<p>' . htmlspecialchars(I18n::t('auth.unavailable')) . ' ' . htmlspecialchars($e->getMessage()) . '</p>';
42
echo '<p><a href="index.html">' . htmlspecialchars(I18n::t('auth.backToGame')) . '</a></p>';
43
}
@@ -0,0 +1,43 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
require __DIR__ . '/lib/I18n.php';5
6
try {7
$next = safeNext($_GET['next'] ?? null);8
if ($next) {9
$_SESSION['after_login'] = $next;10
}11
if (localDev() && isset($_GET['test'])) {12
$n = (int) $_GET['test'];13
if ($n < 1 || $n > ALLIANTIES_TEST_USERS) {14
throw new RuntimeException('Onbekende testgebruiker.');15
}16
$who = 'test_user_' . $n;17
loginUser('local:' . $who, $who, 'images/avatars/' . $who . '.svg');18
$dest = $_SESSION['after_login'] ?? (is_string($next) ? $next : 'index.html');19
unset($_SESSION['after_login']);20
header('Location: ' . $dest);21
exit;22
}23
if (!authConfigured()) {24
header('Location: index.html?auth=unconfigured');25
exit;26
}27
$cfg = config();28
$_SESSION['oauth_state'] = bin2hex(random_bytes(32));29
$_SESSION['oauth_started'] = time();30
header('Location: ' . authUrl() . '/oauth/authorize?' . http_build_query([31
'client_id' => $cfg['client_id'],32
'redirect_uri' => baseUrl() . '/callback.php',33
'response_type' => 'code',34
'state' => $_SESSION['oauth_state'],35
]));36
} catch (Throwable $e) {37
http_response_code(503);38
header('Content-Type: text/html; charset=utf-8');39
$lang = I18n::htmlLang();40
echo '<!DOCTYPE html><html lang="' . htmlspecialchars($lang) . '"><meta charset="utf-8"><title>Allianties</title>';41
echo '<p>' . htmlspecialchars(I18n::t('auth.unavailable')) . ' ' . htmlspecialchars($e->getMessage()) . '</p>';42
echo '<p><a href="index.html">' . htmlspecialchars(I18n::t('auth.backToGame')) . '</a></p>';43
}@@ -0,0 +1,52 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
require __DIR__ . '/lib/I18n.php';
5
6
try {
7
$state = $_GET['state'] ?? null;
8
if (!is_string($state) || !isset($_SESSION['oauth_state'])
9
|| !hash_equals((string) $_SESSION['oauth_state'], $state)
10
|| time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) {
11
throw new RuntimeException('Ongeldige of verlopen login.');
12
}
13
unset($_SESSION['oauth_state'], $_SESSION['oauth_started']);
14
$code = $_GET['code'] ?? null;
15
if (!is_string($code) || $code === '') {
16
throw new RuntimeException('De login is niet afgerond.');
17
}
18
$cfg = config();
19
$token = authRequest('/oauth/token', [
20
'grant_type' => 'authorization_code',
21
'code' => $code,
22
'client_id' => $cfg['client_id'],
23
'client_secret' => $cfg['client_secret'],
24
'redirect_uri' => baseUrl() . '/callback.php',
25
]);
26
if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {
27
throw new RuntimeException('Geen toegangstoken ontvangen.');
28
}
29
$me = authRequest('/api/me', null, $token['access_token']);
30
if (!isset($me['user']) || !is_array($me['user'])) {
31
throw new RuntimeException('Het profiel ontbreekt.');
32
}
33
[$id, $name, $avatar] = authIdentity($me['user']);
34
loginUser($id, $name, $avatar);
35
$_SESSION['token'] = $token['access_token'];
36
$_SESSION['expires'] = time() + (int) $token['expires_in'];
37
if ((int) $token['expires_in'] < 86400) {
38
// Keep our session for the full TTL even if the access token is shorter;
39
// we only needed it to identify the user.
40
$_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL;
41
}
42
$dest = $_SESSION['after_login'] ?? 'index.html';
43
unset($_SESSION['after_login']);
44
header('Location: ' . $dest);
45
} catch (Throwable $e) {
46
http_response_code(401);
47
header('Content-Type: text/html; charset=utf-8');
48
$lang = I18n::htmlLang();
49
echo '<!DOCTYPE html><html lang="' . htmlspecialchars($lang) . '"><meta charset="utf-8"><title>Allianties</title>';
50
echo htmlspecialchars(I18n::t('auth.failed')) . ' ' . htmlspecialchars($e->getMessage());
51
echo ' <a href="auth.php">' . htmlspecialchars(I18n::t('auth.retry')) . '</a> · <a href="index.html">' . htmlspecialchars(I18n::t('auth.back')) . '</a>';
52
}
@@ -0,0 +1,52 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
require __DIR__ . '/lib/I18n.php';5
6
try {7
$state = $_GET['state'] ?? null;8
if (!is_string($state) || !isset($_SESSION['oauth_state'])9
|| !hash_equals((string) $_SESSION['oauth_state'], $state)10
|| time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) {11
throw new RuntimeException('Ongeldige of verlopen login.');12
}13
unset($_SESSION['oauth_state'], $_SESSION['oauth_started']);14
$code = $_GET['code'] ?? null;15
if (!is_string($code) || $code === '') {16
throw new RuntimeException('De login is niet afgerond.');17
}18
$cfg = config();19
$token = authRequest('/oauth/token', [20
'grant_type' => 'authorization_code',21
'code' => $code,22
'client_id' => $cfg['client_id'],23
'client_secret' => $cfg['client_secret'],24
'redirect_uri' => baseUrl() . '/callback.php',25
]);26
if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {27
throw new RuntimeException('Geen toegangstoken ontvangen.');28
}29
$me = authRequest('/api/me', null, $token['access_token']);30
if (!isset($me['user']) || !is_array($me['user'])) {31
throw new RuntimeException('Het profiel ontbreekt.');32
}33
[$id, $name, $avatar] = authIdentity($me['user']);34
loginUser($id, $name, $avatar);35
$_SESSION['token'] = $token['access_token'];36
$_SESSION['expires'] = time() + (int) $token['expires_in'];37
if ((int) $token['expires_in'] < 86400) {38
// Keep our session for the full TTL even if the access token is shorter;39
// we only needed it to identify the user.40
$_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL;41
}42
$dest = $_SESSION['after_login'] ?? 'index.html';43
unset($_SESSION['after_login']);44
header('Location: ' . $dest);45
} catch (Throwable $e) {46
http_response_code(401);47
header('Content-Type: text/html; charset=utf-8');48
$lang = I18n::htmlLang();49
echo '<!DOCTYPE html><html lang="' . htmlspecialchars($lang) . '"><meta charset="utf-8"><title>Allianties</title>';50
echo htmlspecialchars(I18n::t('auth.failed')) . ' ' . htmlspecialchars($e->getMessage());51
echo ' <a href="auth.php">' . htmlspecialchars(I18n::t('auth.retry')) . '</a> · <a href="index.html">' . htmlspecialchars(I18n::t('auth.back')) . '</a>';52
}@@ -0,0 +1,3 @@
1
*
2
!.htaccess
3
!.gitignore
@@ -0,0 +1,3 @@1
*2
!.htaccess3
!.gitignore@@ -0,0 +1 @@
1
Require all denied
@@ -0,0 +1 @@1
Require all denied@@ -0,0 +1,1615 @@
1
<?php
2
declare(strict_types=1);
3
4
/**
5
* Pure, deterministic Allianties rule engine.
6
* Server and tests share this. The client replays the same event log.
7
*
8
* Extra rules (jury, shrinking arena, and future ones) are toggles on the
9
* game's `rules` object and are applied only from here, so they can be
10
* turned on or off without touching the rest of the stack.
11
*/
12
final class Engine
13
{
14
public const TZ = 'Europe/Amsterdam';
15
public const STARTING_LIVES = 3;
16
public const STARTING_RANGE = 2;
17
public const STARTING_AP = 1;
18
public const MIN_PLAYERS = 2;
19
public const MAX_PLAYERS = 16;
20
public const MIN_GRID = 6;
21
public const MIN_ARENA = 3;
22
public const DEFAULT_SHRINK_DAYS = 7;
23
public const MIN_SHRINK_DAYS = 1;
24
public const MAX_SHRINK_DAYS = 30;
25
public const NOTE_MAX = 2000;
26
public const CHAT_MAX = 1000;
27
public const NAME_MAX = 64;
28
public const CODE_LEN = 6;
29
30
/** @var list<string> Allowed vis_shots values; first is the default. */
31
public const VIS_SHOTS = ['public', 'elim_public', 'known_target', 'elim_known_target'];
32
/** @var list<string> */
33
public const VIS_GIFTS = ['public', 'known_recipient', 'anonymous'];
34
/** @var list<string> */
35
public const VIS_AP = ['public', 'hidden'];
36
/** @var list<string> */
37
public const VIS_RANGE = ['public', 'known_in_range', 'hidden'];
38
/** @var list<string> */
39
public const VIS_LIVES = ['public', 'hidden'];
40
41
/** @var list<string> */
42
public const COLORS = [
43
'#e74c3c', '#3498db', '#2ecc71', '#f1c40f',
44
'#9b59b6', '#e67e22', '#1abc9c', '#e91e63',
45
'#00bcd4', '#8bc34a', '#ff5722', '#3f51b5',
46
'#795548', '#607d8b', '#cddc39', '#ff9800',
47
];
48
49
/** Injected unix timestamp for tests; null means time(). */
50
public static ?int $now = null;
51
52
public static function now(): int
53
{
54
return self::$now ?? time();
55
}
56
57
public static function defaultRules(): array
58
{
59
return [
60
'jury' => true,
61
'shrinking_arena' => false,
62
'shrink_interval_days' => self::DEFAULT_SHRINK_DAYS,
63
'ceasefire' => false,
64
'ceasefire_ranges' => [],
65
'ap_loot' => false,
66
'ap_time' => '00:00',
67
'vis_shots' => 'public',
68
'vis_gifts' => 'public',
69
'vis_ap' => 'public',
70
'vis_range' => 'public',
71
'vis_lives' => 'public',
72
];
73
}
74
75
public static function normalizeRules(array $raw): array
76
{
77
$d = self::defaultRules();
78
$d['jury'] = array_key_exists('jury', $raw) ? (bool) $raw['jury'] : true;
79
$d['shrinking_arena'] = !empty($raw['shrinking_arena']);
80
$n = isset($raw['shrink_interval_days']) ? (int) $raw['shrink_interval_days'] : self::DEFAULT_SHRINK_DAYS;
81
if ($n < self::MIN_SHRINK_DAYS) {
82
$n = self::MIN_SHRINK_DAYS;
83
}
84
if ($n > self::MAX_SHRINK_DAYS) {
85
$n = self::MAX_SHRINK_DAYS;
86
}
87
$d['shrink_interval_days'] = $n;
88
$d['ceasefire'] = self::asBool($raw['ceasefire'] ?? false);
89
$d['ceasefire_ranges'] = self::normalizeRanges($raw['ceasefire_ranges'] ?? []);
90
$d['ap_loot'] = self::asBool($raw['ap_loot'] ?? false);
91
$hm = self::parseHm($raw['ap_time'] ?? '00:00');
92
$d['ap_time'] = $hm ?? '00:00';
93
$d['vis_shots'] = self::visChoice($raw['vis_shots'] ?? null, self::VIS_SHOTS, 'public');
94
$d['vis_gifts'] = self::visChoice($raw['vis_gifts'] ?? null, self::VIS_GIFTS, 'public');
95
$d['vis_ap'] = self::visChoice($raw['vis_ap'] ?? null, self::VIS_AP, 'public');
96
$d['vis_range'] = self::visChoice($raw['vis_range'] ?? null, self::VIS_RANGE, 'public');
97
$d['vis_lives'] = self::visChoice($raw['vis_lives'] ?? null, self::VIS_LIVES, 'public');
98
return $d;
99
}
100
101
/** Square board: at least 6, about 6 tiles of space per player. */
102
public static function gridSize(int $n): int
103
{
104
if ($n < 1) {
105
$n = 1;
106
}
107
return max(self::MIN_GRID, (int) ceil(sqrt($n * 6)));
108
}
109
110
/** Largest inset that still leaves a MIN_ARENA playable square. */
111
public static function maxInset(int $size): int
112
{
113
return max(0, (int) floor(($size - self::MIN_ARENA) / 2));
114
}
115
116
/**
117
* Place players evenly on a ring around the centre, on unique tiles,
118
* starting at the top and going clockwise. Never on the same tile.
119
*
120
* @return list<array{x:int,y:int}>
121
*/
122
public static function startingPositions(int $n, int $size): array
123
{
124
if ($n < 1) {
125
return [];
126
}
127
$cx = ($size - 1) / 2.0;
128
$cy = ($size - 1) / 2.0;
129
$radius = max(1.0, ($size - 1) / 2.0 - 1.0);
130
$used = [];
131
$out = [];
132
for ($i = 0; $i < $n; $i++) {
133
$ang = -M_PI / 2 + ($i * 2 * M_PI / $n);
134
$fx = $cx + $radius * cos($ang);
135
$fy = $cy + $radius * sin($ang);
136
$x = (int) max(0, min($size - 1, (int) round($fx)));
137
$y = (int) max(0, min($size - 1, (int) round($fy)));
138
$key = $x . ',' . $y;
139
if (isset($used[$key])) {
140
$found = false;
141
for ($d = 1; $d < $size * 2 && !$found; $d++) {
142
for ($dx = -$d; $dx <= $d && !$found; $dx++) {
143
for ($dy = -$d; $dy <= $d; $dy++) {
144
if (max(abs($dx), abs($dy)) !== $d) {
145
continue;
146
}
147
$nx = $x + $dx;
148
$ny = $y + $dy;
149
if ($nx < 0 || $ny < 0 || $nx >= $size || $ny >= $size) {
150
continue;
151
}
152
$k2 = $nx . ',' . $ny;
153
if (!isset($used[$k2])) {
154
$x = $nx;
155
$y = $ny;
156
$key = $k2;
157
$found = true;
158
break;
159
}
160
}
161
}
162
}
163
}
164
$used[$key] = true;
165
$out[] = ['x' => $x, 'y' => $y];
166
}
167
return $out;
168
}
169
170
public static function chebyshev(int $x1, int $y1, int $x2, int $y2): int
171
{
172
return max(abs($x1 - $x2), abs($y1 - $y2));
173
}
174
175
public static function inBounds(int $size, int $x, int $y): bool
176
{
177
return $x >= 0 && $y >= 0 && $x < $size && $y < $size;
178
}
179
180
public static function isPassable(int $size, int $inset, int $x, int $y): bool
181
{
182
if (!self::inBounds($size, $x, $y)) {
183
return false;
184
}
185
return $x >= $inset && $y >= $inset && $x < $size - $inset && $y < $size - $inset;
186
}
187
188
/**
189
* Next occurrence of a Europe/Amsterdam wall-clock time strictly after $from.
190
* Used for the per-lobby daily AP time (default 00:00).
191
* If that clock time is skipped by a spring-forward DST gap, PHP's
192
* DateTime::setTime lands on the first valid instant after the gap.
193
*/
194
public static function nextDistribution(int $from, ?string $hm = null): int
195
{
196
$hm = self::parseHm($hm ?? '00:00') ?? '00:00';
197
[$h, $min] = array_map('intval', explode(':', $hm));
198
$tz = new DateTimeZone(self::TZ);
199
$dt = (new DateTime('@' . $from))->setTimezone($tz);
200
$candidate = clone $dt;
201
$candidate->setTime($h, $min, 0);
202
if ($candidate->getTimestamp() <= $from) {
203
$candidate->modify('+1 day');
204
$candidate->setTime($h, $min, 0);
205
}
206
return $candidate->getTimestamp();
207
}
208
209
/** Next 00:00 Europe/Amsterdam strictly after $from. */
210
public static function nextMidnight(int $from): int
211
{
212
return self::nextDistribution($from, '00:00');
213
}
214
215
/** Today's 00:00 Amsterdam on or before $from. */
216
public static function thisMidnight(int $from): int
217
{
218
$tz = new DateTimeZone(self::TZ);
219
$dt = new DateTime('@' . $from);
220
$dt->setTimezone($tz);
221
$dt->setTime(0, 0, 0);
222
return $dt->getTimestamp();
223
}
224
225
/**
226
* A new lobby (status=lobby) with the host as first member.
227
*/
228
public static function newLobby(
229
string $id,
230
string $code,
231
string $hostId,
232
string $hostName,
233
?string $avatar,
234
array $rules,
235
int $now
236
): array {
237
$rules = self::normalizeRules($rules);
238
return [
239
'id' => $id,
240
'code' => $code,
241
'host_id' => $hostId,
242
'status' => 'lobby',
243
'created_at' => $now,
244
'started_at' => null,
245
'finished_at' => null,
246
'rules' => $rules,
247
'grid' => self::MIN_GRID,
248
'day' => 0,
249
'next_distribution_at' => null,
250
'arena_inset' => 0,
251
'winner_id' => null,
252
'draw' => false,
253
'players' => [
254
self::newPlayer($hostId, $hostName, $avatar, 0, $now),
255
],
256
'events' => [],
257
'votes' => [],
258
'notes' => [],
259
'messages' => [],
260
'event_seq' => 0,
261
'version' => 1,
262
];
263
}
264
265
public static function newPlayer(string $id, string $name, ?string $avatar, int $colorIndex, int $now): array
266
{
267
$colors = self::COLORS;
268
$color = $colors[$colorIndex % count($colors)];
269
return [
270
'id' => $id,
271
'name' => $name,
272
'avatar' => $avatar,
273
'color' => $color,
274
'color_index' => $colorIndex,
275
'x' => 0,
276
'y' => 0,
277
'lives' => self::STARTING_LIVES,
278
'ap' => 0,
279
'range' => self::STARTING_RANGE,
280
'alive' => true,
281
'surrendered' => false,
282
'joined_at' => $now,
283
];
284
}
285
286
public static function playerIndex(array $game, string $userId): ?int
287
{
288
foreach ($game['players'] as $i => $p) {
289
if ($p['id'] === $userId) {
290
return (int) $i;
291
}
292
}
293
return null;
294
}
295
296
public static function player(array $game, string $userId): ?array
297
{
298
$i = self::playerIndex($game, $userId);
299
return $i === null ? null : $game['players'][$i];
300
}
301
302
/** @return list<array> */
303
public static function living(array $game): array
304
{
305
return array_values(array_filter($game['players'], fn ($p) => !empty($p['alive'])));
306
}
307
308
public static function occupiedByLiving(array $game, int $x, int $y, ?string $except = null): ?string
309
{
310
foreach ($game['players'] as $p) {
311
if (empty($p['alive'])) {
312
continue;
313
}
314
if ($except !== null && $p['id'] === $except) {
315
continue;
316
}
317
if ((int) $p['x'] === $x && (int) $p['y'] === $y) {
318
return $p['id'];
319
}
320
}
321
return null;
322
}
323
324
public static function pushEvent(array &$game, string $type, array $data, int $now): array
325
{
326
$game['event_seq'] = (int) ($game['event_seq'] ?? 0) + 1;
327
$game['version'] = (int) ($game['version'] ?? 0) + 1;
328
$ev = array_merge([
329
'id' => $game['event_seq'],
330
't' => $now,
331
'type' => $type,
332
], $data);
333
$game['events'][] = $ev;
334
return $ev;
335
}
336
337
/**
338
* Join a lobby. Throws RuntimeException with a stable error code.
339
*/
340
public static function join(array $game, string $userId, string $name, ?string $avatar, int $now): array
341
{
342
if ($game['status'] !== 'lobby') {
343
throw new RuntimeException('game_started');
344
}
345
if (self::playerIndex($game, $userId) !== null) {
346
return $game; // already in
347
}
348
if (count($game['players']) >= self::MAX_PLAYERS) {
349
throw new RuntimeException('lobby_full');
350
}
351
$game['players'][] = self::newPlayer($userId, $name, $avatar, count($game['players']), $now);
352
return $game;
353
}
354
355
public static function leaveLobby(array $game, string $userId, int $now): ?array
356
{
357
if ($game['status'] !== 'lobby') {
358
throw new RuntimeException('game_started');
359
}
360
$idx = self::playerIndex($game, $userId);
361
if ($idx === null) {
362
return $game;
363
}
364
array_splice($game['players'], $idx, 1);
365
if (count($game['players']) === 0) {
366
return null; // delete lobby
367
}
368
// Re-index colours; if host left, earliest joiner becomes host.
369
foreach ($game['players'] as $i => &$p) {
370
$p['color_index'] = $i;
371
$p['color'] = self::COLORS[$i % count(self::COLORS)];
372
}
373
unset($p);
374
if ($game['host_id'] === $userId) {
375
$game['host_id'] = $game['players'][0]['id'];
376
}
377
return $game;
378
}
379
380
public static function setLobbyRules(array $game, string $userId, array $rules): array
381
{
382
if ($game['status'] !== 'lobby') {
383
throw new RuntimeException('game_started');
384
}
385
if ($game['host_id'] !== $userId) {
386
throw new RuntimeException('not_host');
387
}
388
$game['rules'] = self::normalizeRules(array_merge($game['rules'], $rules));
389
return $game;
390
}
391
392
public static function start(array $game, string $userId, int $now): array
393
{
394
if ($game['status'] !== 'lobby') {
395
throw new RuntimeException('game_started');
396
}
397
if ($game['host_id'] !== $userId) {
398
throw new RuntimeException('not_host');
399
}
400
$n = count($game['players']);
401
if ($n < self::MIN_PLAYERS) {
402
throw new RuntimeException('min_players');
403
}
404
$size = self::gridSize($n);
405
$pos = self::startingPositions($n, $size);
406
$game['grid'] = $size;
407
$game['status'] = 'running';
408
$game['started_at'] = $now;
409
$game['day'] = 0;
410
$game['arena_inset'] = 0;
411
$game['next_distribution_at'] = self::nextDistribution($now, $game['rules']['ap_time'] ?? '00:00');
412
$placed = [];
413
foreach ($game['players'] as $i => &$p) {
414
$p['x'] = $pos[$i]['x'];
415
$p['y'] = $pos[$i]['y'];
416
$p['lives'] = self::STARTING_LIVES;
417
$p['ap'] = self::STARTING_AP;
418
$p['range'] = self::STARTING_RANGE;
419
$p['alive'] = true;
420
$p['surrendered'] = false;
421
$placed[] = [
422
'id' => $p['id'],
423
'x' => $p['x'],
424
'y' => $p['y'],
425
'color' => $p['color'],
426
'name' => $p['name'],
427
];
428
}
429
unset($p);
430
self::pushEvent($game, 'start', [
431
'grid' => $size,
432
'players' => $placed,
433
'rules' => $game['rules'],
434
'spend' => false,
435
], $now);
436
return $game;
437
}
438
439
/**
440
* Catch up daily distributions (AP, jury, shrink) until $now.
441
* Safe to call on every request.
442
*/
443
public static function applyDue(array $game, int $now): array
444
{
445
if ($game['status'] !== 'running') {
446
return $game;
447
}
448
$guard = 0;
449
while (
450
isset($game['next_distribution_at'])
451
&& $game['next_distribution_at'] !== null
452
&& (int) $game['next_distribution_at'] <= $now
453
&& $game['status'] === 'running'
454
&& $guard < 4000
455
) {
456
$at = (int) $game['next_distribution_at'];
457
$game = self::distributeOneDay($game, $at);
458
$game['next_distribution_at'] = self::nextDistribution($at, $game['rules']['ap_time'] ?? '00:00');
459
$guard++;
460
}
461
return $game;
462
}
463
464
public static function daysUntilShrink(array $game): ?int
465
{
466
if ($game['status'] !== 'running' || empty($game['rules']['shrinking_arena'])) {
467
return null;
468
}
469
$size = (int) $game['grid'];
470
if ((int) $game['arena_inset'] >= self::maxInset($size)) {
471
return null;
472
}
473
$interval = (int) $game['rules']['shrink_interval_days'];
474
$day = (int) $game['day'];
475
// Next shrink at day = k*interval for k>=1, i.e. after `interval` midnights.
476
$nextAt = (int) (ceil(($day + 1) / $interval) * $interval);
477
if ($nextAt <= $day) {
478
$nextAt += $interval;
479
}
480
return $nextAt - $day;
481
}
482
483
private static function distributeOneDay(array $game, int $at): array
484
{
485
$game['day'] = (int) $game['day'] + 1;
486
$day = (int) $game['day'];
487
$grants = [];
488
$jury = null;
489
490
// 1. Shrink first so someone who dies today does not receive AP.
491
$shrink = null;
492
if (!empty($game['rules']['shrinking_arena'])) {
493
$interval = (int) $game['rules']['shrink_interval_days'];
494
$size = (int) $game['grid'];
495
$inset = (int) $game['arena_inset'];
496
if ($interval > 0 && $day % $interval === 0 && $inset < self::maxInset($size)) {
497
$result = self::applyShrink($game, $at);
498
$game = $result['game'];
499
$shrink = $result['report'];
500
}
501
}
502
503
if ($game['status'] !== 'running') {
504
// Finished mid-shrink; still record the day event.
505
self::pushEvent($game, 'daily', [
506
'day' => $day,
507
'grants' => $grants,
508
'jury' => $jury,
509
'shrink' => $shrink,
510
'spend' => false,
511
], $at);
512
return $game;
513
}
514
515
// 2. Jury: unique or tied living targets each get +1. Votes stay secret.
516
if (!empty($game['rules']['jury'])) {
517
$jury = self::tallyJury($game);
518
}
519
520
// 3. Grant 1 AP to every living player, plus jury bonus.
521
foreach ($game['players'] as &$p) {
522
if (empty($p['alive'])) {
523
continue;
524
}
525
$add = 1;
526
if ($jury && in_array($p['id'], $jury['winners'], true)) {
527
$add += 1;
528
}
529
$p['ap'] = (int) $p['ap'] + $add;
530
$grants[$p['id']] = $add;
531
}
532
unset($p);
533
534
// Votes reset for the new day (changeable until the next distribution).
535
$game['votes'] = [];
536
537
self::pushEvent($game, 'daily', [
538
'day' => $day,
539
'grants' => $grants,
540
'jury' => $jury,
541
'shrink' => $shrink,
542
'spend' => false,
543
], $at);
544
545
$game = self::checkEnd($game, $at);
546
return $game;
547
}
548
549
/**
550
* Tally current votes. Winners are living players with the strictly
551
* highest count; on a tie every tied player is a winner (each +1 AP).
552
* Players with zero votes never win, even if nobody voted (no award).
553
*
554
* @return array{winners:list<string>,counts:array<string,int>,votes_cast:int}|null
555
*/
556
public static function tallyJury(array $game): ?array
557
{
558
$livingIds = [];
559
foreach (self::living($game) as $p) {
560
$livingIds[$p['id']] = true;
561
}
562
$counts = [];
563
$cast = 0;
564
foreach ($game['votes'] as $voter => $target) {
565
if (!is_string($voter) || !is_string($target)) {
566
continue;
567
}
568
if (!isset($livingIds[$target])) {
569
continue;
570
}
571
// Voter should be a dead participant.
572
$v = self::player($game, $voter);
573
if (!$v || !empty($v['alive'])) {
574
continue;
575
}
576
$counts[$target] = ($counts[$target] ?? 0) + 1;
577
$cast++;
578
}
579
if ($cast === 0 || $counts === []) {
580
return ['winners' => [], 'counts' => $counts, 'votes_cast' => 0];
581
}
582
$max = max($counts);
583
$winners = [];
584
foreach ($counts as $id => $c) {
585
if ($c === $max) {
586
$winners[] = $id;
587
}
588
}
589
sort($winners);
590
return ['winners' => $winners, 'counts' => $counts, 'votes_cast' => $cast];
591
}
592
593
/**
594
* Advance arena_inset by 1. Players on the new outer ring lose 1 life
595
* and, if still alive, are pushed to the nearest free passable tile.
596
*
597
* @return array{game:array,report:array}
598
*/
599
public static function applyShrink(array $game, int $now): array
600
{
601
$size = (int) $game['grid'];
602
$newInset = (int) $game['arena_inset'] + 1;
603
if ($newInset > self::maxInset($size)) {
604
return ['game' => $game, 'report' => null];
605
}
606
$game['arena_inset'] = $newInset;
607
$moved = [];
608
$hurt = [];
609
$killed = [];
610
$crushed = [];
611
612
// Deterministic order: by player id.
613
$indices = [];
614
foreach ($game['players'] as $i => $p) {
615
$indices[] = $i;
616
}
617
usort($indices, function ($a, $b) use ($game) {
618
return strcmp($game['players'][$a]['id'], $game['players'][$b]['id']);
619
});
620
621
foreach ($indices as $i) {
622
$p = $game['players'][$i];
623
if (empty($p['alive'])) {
624
continue;
625
}
626
$x = (int) $p['x'];
627
$y = (int) $p['y'];
628
if (self::isPassable($size, $newInset, $x, $y)) {
629
continue;
630
}
631
// Standing on the new ring: take 1 damage.
632
$p['lives'] = (int) $p['lives'] - 1;
633
$hurt[] = $p['id'];
634
if ($p['lives'] <= 0) {
635
$p['lives'] = 0;
636
$p['alive'] = false;
637
$p['ap'] = 0;
638
$killed[] = $p['id'];
639
$game['players'][$i] = $p;
640
self::pushEvent($game, 'death', [
641
'player' => $p['id'],
642
'cause' => 'shrink',
643
'spend' => false,
644
], $now);
645
continue;
646
}
647
$dest = self::nearestFreeTile($game, $size, $newInset, $x, $y, $p['id']);
648
if ($dest === null) {
649
// No free inward tile: crushed, eliminated.
650
$p['lives'] = 0;
651
$p['alive'] = false;
652
$p['ap'] = 0;
653
$killed[] = $p['id'];
654
$crushed[] = $p['id'];
655
$game['players'][$i] = $p;
656
self::pushEvent($game, 'death', [
657
'player' => $p['id'],
658
'cause' => 'crushed',
659
'spend' => false,
660
], $now);
661
continue;
662
}
663
$from = ['x' => $x, 'y' => $y];
664
$p['x'] = $dest['x'];
665
$p['y'] = $dest['y'];
666
$moved[] = ['id' => $p['id'], 'from' => $from, 'to' => $dest];
667
$game['players'][$i] = $p;
668
}
669
670
$report = [
671
'inset' => $newInset,
672
'hurt' => $hurt,
673
'killed' => $killed,
674
'crushed' => $crushed,
675
'moved' => $moved,
676
];
677
self::pushEvent($game, 'shrink', array_merge($report, ['spend' => false]), $now);
678
$game = self::checkEnd($game, $now);
679
return ['game' => $game, 'report' => $report];
680
}
681
682
/**
683
* Nearest free passable tile, Chebyshev first, then Euclidean to centre,
684
* then (y, x) for a stable leftover tie.
685
*
686
* @return array{x:int,y:int}|null
687
*/
688
public static function nearestFreeTile(
689
array $game,
690
int $size,
691
int $inset,
692
int $fromX,
693
int $fromY,
694
string $moverId
695
): ?array {
696
$cx = ($size - 1) / 2.0;
697
$cy = ($size - 1) / 2.0;
698
$best = null;
699
$bestKey = null;
700
for ($x = $inset; $x < $size - $inset; $x++) {
701
for ($y = $inset; $y < $size - $inset; $y++) {
702
if (self::occupiedByLiving($game, $x, $y, $moverId) !== null) {
703
continue;
704
}
705
$d = self::chebyshev($fromX, $fromY, $x, $y);
706
$dc = ($x - $cx) * ($x - $cx) + ($y - $cy) * ($y - $cy);
707
$key = sprintf('%04d-%012.6f-%04d-%04d', $d, $dc, $y, $x);
708
if ($bestKey === null || $key < $bestKey) {
709
$bestKey = $key;
710
$best = ['x' => $x, 'y' => $y];
711
}
712
}
713
}
714
return $best;
715
}
716
717
public static function checkEnd(array $game, int $now): array
718
{
719
if ($game['status'] !== 'running') {
720
return $game;
721
}
722
$alive = self::living($game);
723
if (count($alive) === 1) {
724
$game['status'] = 'finished';
725
$game['finished_at'] = $now;
726
$game['winner_id'] = $alive[0]['id'];
727
$game['draw'] = false;
728
self::pushEvent($game, 'win', [
729
'player' => $alive[0]['id'],
730
'spend' => false,
731
], $now);
732
} elseif (count($alive) === 0) {
733
$game['status'] = 'finished';
734
$game['finished_at'] = $now;
735
$game['winner_id'] = null;
736
$game['draw'] = true;
737
self::pushEvent($game, 'draw', ['spend' => false], $now);
738
}
739
return $game;
740
}
741
742
/**
743
* Legal actions for a viewer (after applyDue).
744
*
745
* @return array{
746
* move:list<array{x:int,y:int}>,
747
* shoot:list<string>,
748
* give:list<string>,
749
* upgrade:bool,
750
* surrender:bool,
751
* vote:list<string>|null,
752
* my_vote:?string
753
* }
754
*/
755
public static function legal(array $game, string $userId, ?int $now = null): array
756
{
757
$now = $now ?? self::now();
758
759
$empty = [
760
'move' => [],
761
'shoot' => [],
762
'give' => [],
763
'upgrade' => false,
764
'surrender' => false,
765
'vote' => null,
766
'my_vote' => null,
767
'ceasefire' => false,
768
];
769
if ($game['status'] !== 'running') {
770
return $empty;
771
}
772
$me = self::player($game, $userId);
773
if (!$me) {
774
return $empty;
775
}
776
$size = (int) $game['grid'];
777
$inset = (int) $game['arena_inset'];
778
if (empty($me['alive'])) {
779
$vote = null;
780
$myVote = null;
781
if (!empty($game['rules']['jury'])) {
782
$vote = [];
783
foreach (self::living($game) as $p) {
784
$vote[] = $p['id'];
785
}
786
$v = $game['votes'][$userId] ?? null;
787
$myVote = is_string($v) ? $v : null;
788
}
789
$empty['vote'] = $vote;
790
$empty['my_vote'] = $myVote;
791
return $empty;
792
}
793
$empty['surrender'] = true;
794
if ((int) $me['ap'] < 1) {
795
return $empty;
796
}
797
// Moves: 8 neighbours.
798
for ($dx = -1; $dx <= 1; $dx++) {
799
for ($dy = -1; $dy <= 1; $dy++) {
800
if ($dx === 0 && $dy === 0) {
801
continue;
802
}
803
$x = (int) $me['x'] + $dx;
804
$y = (int) $me['y'] + $dy;
805
if (!self::isPassable($size, $inset, $x, $y)) {
806
continue;
807
}
808
if (self::occupiedByLiving($game, $x, $y, $userId) !== null) {
809
continue;
810
}
811
$empty['move'][] = ['x' => $x, 'y' => $y];
812
}
813
}
814
$range = (int) $me['range'];
815
foreach ($game['players'] as $p) {
816
if ($p['id'] === $userId || empty($p['alive'])) {
817
continue;
818
}
819
$d = self::chebyshev((int) $me['x'], (int) $me['y'], (int) $p['x'], (int) $p['y']);
820
if ($d <= $range) {
821
$empty['shoot'][] = $p['id'];
822
$empty['give'][] = $p['id'];
823
}
824
}
825
// Upgrade: cap at the board's max Chebyshev distance (covers the board).
826
$maxRange = max(1, $size - 1);
827
$empty['upgrade'] = (int) $me['range'] < $maxRange;
828
if (self::ceasefireActive($game, $now)) {
829
$empty['shoot'] = [];
830
$empty['ceasefire'] = true;
831
} else {
832
$empty['ceasefire'] = false;
833
}
834
return $empty;
835
}
836
837
/**
838
* Apply a player action. $action = {type, ...}.
839
* Types: move, shoot, give, upgrade, surrender, vote.
840
*/
841
public static function applyAction(array $game, string $userId, array $action, int $now): array
842
{
843
$game = self::applyDue($game, $now);
844
if ($game['status'] !== 'running') {
845
throw new RuntimeException('game_finished');
846
}
847
$type = (string) ($action['type'] ?? '');
848
$me = self::player($game, $userId);
849
if (!$me) {
850
throw new RuntimeException('not_in_game');
851
}
852
853
if ($type === 'vote') {
854
return self::actVote($game, $userId, $action, $now);
855
}
856
if ($type === 'surrender') {
857
return self::actSurrender($game, $userId, $now);
858
}
859
if (empty($me['alive'])) {
860
throw new RuntimeException('dead');
861
}
862
$legal = self::legal($game, $userId, $now);
863
return match ($type) {
864
'move' => self::actMove($game, $userId, $action, $legal, $now),
865
'shoot' => self::actShoot($game, $userId, $action, $legal, $now),
866
'give' => self::actGive($game, $userId, $action, $legal, $now),
867
'upgrade' => self::actUpgrade($game, $userId, $legal, $now),
868
default => throw new RuntimeException('unknown_action'),
869
};
870
}
871
872
private static function spendAp(array &$game, string $userId, int $n = 1): void
873
{
874
$i = self::playerIndex($game, $userId);
875
if ($i === null || (int) $game['players'][$i]['ap'] < $n) {
876
throw new RuntimeException('no_ap');
877
}
878
$game['players'][$i]['ap'] = (int) $game['players'][$i]['ap'] - $n;
879
}
880
881
private static function actMove(array $game, string $userId, array $action, array $legal, int $now): array
882
{
883
$x = (int) ($action['x'] ?? -1);
884
$y = (int) ($action['y'] ?? -1);
885
$ok = false;
886
foreach ($legal['move'] as $t) {
887
if ((int) $t['x'] === $x && (int) $t['y'] === $y) {
888
$ok = true;
889
break;
890
}
891
}
892
if (!$ok) {
893
throw new RuntimeException('invalid_move');
894
}
895
self::spendAp($game, $userId, 1);
896
$i = self::playerIndex($game, $userId);
897
$from = ['x' => (int) $game['players'][$i]['x'], 'y' => (int) $game['players'][$i]['y']];
898
$game['players'][$i]['x'] = $x;
899
$game['players'][$i]['y'] = $y;
900
self::pushEvent($game, 'move', [
901
'player' => $userId,
902
'from' => $from,
903
'to' => ['x' => $x, 'y' => $y],
904
'spend' => true,
905
], $now);
906
return $game;
907
}
908
909
private static function actShoot(array $game, string $userId, array $action, array $legal, int $now): array
910
{
911
if (self::ceasefireActive($game, $now)) {
912
throw new RuntimeException('ceasefire');
913
}
914
$targetId = (string) ($action['target'] ?? '');
915
if (!in_array($targetId, $legal['shoot'], true)) {
916
throw new RuntimeException('out_of_range');
917
}
918
self::spendAp($game, $userId, 1);
919
$ti = self::playerIndex($game, $targetId);
920
$game['players'][$ti]['lives'] = (int) $game['players'][$ti]['lives'] - 1;
921
$livesLeft = (int) $game['players'][$ti]['lives'];
922
$killed = false;
923
$loot = 0;
924
if ($livesLeft <= 0) {
925
$game['players'][$ti]['lives'] = 0;
926
$game['players'][$ti]['alive'] = false;
927
$killed = true;
928
// AP loot (lobby option, default off): shooter takes the target's
929
// remaining AP on an eliminating shot only. Shrink/surrender do not loot.
930
if (!empty($game['rules']['ap_loot'])) {
931
$loot = max(0, (int) $game['players'][$ti]['ap']);
932
if ($loot > 0) {
933
$si = self::playerIndex($game, $userId);
934
if ($si !== null) {
935
$game['players'][$si]['ap'] = (int) $game['players'][$si]['ap'] + $loot;
936
}
937
}
938
}
939
$game['players'][$ti]['ap'] = 0;
940
}
941
$shootEv = [
942
'player' => $userId,
943
'target' => $targetId,
944
'lives_left' => max(0, $livesLeft),
945
'damage' => 1,
946
'killed' => $killed,
947
'spend' => true,
948
];
949
if ($loot > 0) {
950
$shootEv['loot'] = $loot;
951
}
952
self::pushEvent($game, 'shoot', $shootEv, $now);
953
if ($killed) {
954
$death = [
955
'player' => $targetId,
956
'cause' => 'shot',
957
'by' => $userId,
958
'spend' => false,
959
];
960
if ($loot > 0) {
961
$death['loot'] = $loot;
962
}
963
self::pushEvent($game, 'death', $death, $now);
964
$game = self::checkEnd($game, $now);
965
}
966
return $game;
967
}
968
969
private static function actGive(array $game, string $userId, array $action, array $legal, int $now): array
970
{
971
$targetId = (string) ($action['target'] ?? '');
972
$amount = (int) ($action['amount'] ?? 0);
973
if (!in_array($targetId, $legal['give'], true)) {
974
throw new RuntimeException('out_of_range');
975
}
976
$me = self::player($game, $userId);
977
if ($amount < 1 || $amount > (int) $me['ap']) {
978
throw new RuntimeException('bad_give');
979
}
980
self::spendAp($game, $userId, $amount);
981
$ti = self::playerIndex($game, $targetId);
982
$game['players'][$ti]['ap'] = (int) $game['players'][$ti]['ap'] + $amount;
983
self::pushEvent($game, 'give', [
984
'player' => $userId,
985
'target' => $targetId,
986
'amount' => $amount,
987
'spend' => true,
988
], $now);
989
return $game;
990
}
991
992
private static function actUpgrade(array $game, string $userId, array $legal, int $now): array
993
{
994
if (empty($legal['upgrade'])) {
995
throw new RuntimeException('invalid_move');
996
}
997
self::spendAp($game, $userId, 1);
998
$i = self::playerIndex($game, $userId);
999
$game['players'][$i]['range'] = (int) $game['players'][$i]['range'] + 1;
1000
self::pushEvent($game, 'upgrade', [
1001
'player' => $userId,
1002
'range' => (int) $game['players'][$i]['range'],
1003
'spend' => true,
1004
], $now);
1005
return $game;
1006
}
1007
1008
private static function actSurrender(array $game, string $userId, int $now): array
1009
{
1010
$i = self::playerIndex($game, $userId);
1011
if (empty($game['players'][$i]['alive'])) {
1012
throw new RuntimeException('dead');
1013
}
1014
$game['players'][$i]['alive'] = false;
1015
$game['players'][$i]['lives'] = 0;
1016
$game['players'][$i]['ap'] = 0;
1017
$game['players'][$i]['surrendered'] = true;
1018
self::pushEvent($game, 'surrender', [
1019
'player' => $userId,
1020
'spend' => false,
1021
], $now);
1022
self::pushEvent($game, 'death', [
1023
'player' => $userId,
1024
'cause' => 'surrender',
1025
'spend' => false,
1026
], $now);
1027
return self::checkEnd($game, $now);
1028
}
1029
1030
private static function actVote(array $game, string $userId, array $action, int $now): array
1031
{
1032
if (empty($game['rules']['jury'])) {
1033
throw new RuntimeException('cannot_vote');
1034
}
1035
$me = self::player($game, $userId);
1036
if (!$me || !empty($me['alive'])) {
1037
throw new RuntimeException('cannot_vote');
1038
}
1039
$targetId = (string) ($action['target'] ?? '');
1040
$t = self::player($game, $targetId);
1041
if (!$t || empty($t['alive'])) {
1042
throw new RuntimeException('bad_vote');
1043
}
1044
$game['votes'][$userId] = $targetId;
1045
// Votes are secret: no public event, but version bumps so polls refresh.
1046
$game['_vote_updated'] = $now;
1047
$game['version'] = (int) ($game['version'] ?? 0) + 1;
1048
return $game;
1049
}
1050
1051
public static function setNote(array $game, string $viewerId, string $subjectId, string $text): array
1052
{
1053
if (self::playerIndex($game, $viewerId) === null) {
1054
throw new RuntimeException('not_in_game');
1055
}
1056
if (self::playerIndex($game, $subjectId) === null) {
1057
throw new RuntimeException('not_in_game');
1058
}
1059
$text = trim($text);
1060
if (mb_strlen($text) > self::NOTE_MAX) {
1061
$text = mb_substr($text, 0, self::NOTE_MAX);
1062
}
1063
$key = $viewerId . "\0" . $subjectId;
1064
if ($text === '') {
1065
unset($game['notes'][$key]);
1066
} else {
1067
$game['notes'][$key] = $text;
1068
}
1069
$game['version'] = (int) ($game['version'] ?? 0) + 1;
1070
return $game;
1071
}
1072
1073
public static function addMessage(array $game, string $fromId, string $toId, string $text, int $now): array
1074
{
1075
if (self::playerIndex($game, $fromId) === null || self::playerIndex($game, $toId) === null) {
1076
throw new RuntimeException('not_in_game');
1077
}
1078
if ($fromId === $toId) {
1079
throw new RuntimeException('invalid_move');
1080
}
1081
$text = trim($text);
1082
if ($text === '' || mb_strlen($text) > self::CHAT_MAX) {
1083
throw new RuntimeException('bad_give');
1084
}
1085
if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $text)) {
1086
throw new RuntimeException('bad_give');
1087
}
1088
$game['messages'][] = [
1089
'id' => count($game['messages']) + 1,
1090
'from' => $fromId,
1091
'to' => $toId,
1092
'text' => $text,
1093
't' => $now,
1094
];
1095
$game['version'] = (int) ($game['version'] ?? 0) + 1;
1096
return $game;
1097
}
1098
1099
/**
1100
* Viewer-specific presentation: hide others' votes and notes, hide
1101
* other people's private chats, include legal actions and shrink ETA.
1102
*/
1103
1104
public static function visChoice(mixed $raw, array $allowed, string $default): string
1105
{
1106
if (is_string($raw) && in_array($raw, $allowed, true)) {
1107
return $raw;
1108
}
1109
return $default;
1110
}
1111
1112
/**
1113
* Per-viewer player card. Own lives/AP/range are always present.
1114
* Movement, identity, and alive/dead are always public.
1115
* Hidden numeric stats are omitted (null) so the API does not leak them.
1116
*
1117
* @param array<string,mixed> $game
1118
* @param array<string,mixed> $p
1119
* @return array<string,mixed>
1120
*/
1121
public static function presentPlayer(array $game, array $p, string $viewerId, string $noteKey): array
1122
{
1123
$rules = $game['rules'] ?? self::defaultRules();
1124
$isSelf = $p['id'] === $viewerId;
1125
$out = [
1126
'id' => $p['id'],
1127
'name' => $p['name'],
1128
'avatar' => $p['avatar'],
1129
'color' => $p['color'],
1130
'x' => (int) $p['x'],
1131
'y' => (int) $p['y'],
1132
'alive' => !empty($p['alive']),
1133
'surrendered' => !empty($p['surrendered']),
1134
'is_you' => $isSelf,
1135
'is_host' => $p['id'] === $game['host_id'],
1136
'note' => $game['notes'][$noteKey] ?? '',
1137
'lives' => null,
1138
'ap' => null,
1139
'range' => null,
1140
];
1141
if ($isSelf || ($rules['vis_lives'] ?? 'public') === 'public') {
1142
$out['lives'] = (int) $p['lives'];
1143
}
1144
if ($isSelf || ($rules['vis_ap'] ?? 'public') === 'public') {
1145
$out['ap'] = (int) $p['ap'];
1146
}
1147
if ($isSelf || ($rules['vis_range'] ?? 'public') === 'public') {
1148
$out['range'] = (int) $p['range'];
1149
} elseif (($rules['vis_range'] ?? 'public') === 'known_in_range'
1150
&& self::viewerInRangeOf($game, $viewerId, $p)) {
1151
$out['range'] = (int) $p['range'];
1152
}
1153
return $out;
1154
}
1155
1156
/**
1157
* True when the viewer is within $subject's current firing range
1158
* (Chebyshev, including diagonals). Used for vis_range = known_in_range.
1159
*
1160
* @param array<string,mixed> $game
1161
* @param array<string,mixed> $subject
1162
*/
1163
public static function viewerInRangeOf(array $game, string $viewerId, array $subject): bool
1164
{
1165
$v = self::player($game, $viewerId);
1166
if ($v === null) {
1167
return false;
1168
}
1169
$dist = self::chebyshev((int) $v['x'], (int) $v['y'], (int) $subject['x'], (int) $subject['y']);
1170
return $dist <= (int) $subject['range'];
1171
}
1172
1173
/**
1174
* Whether $viewerId may see a shot event (who shot whom).
1175
* The shooter always sees their own shot.
1176
*/
1177
public static function canSeeShot(array $rules, string $viewerId, string $shooter, string $target, bool $killed): bool
1178
{
1179
if ($viewerId === $shooter) {
1180
return true;
1181
}
1182
$mode = $rules['vis_shots'] ?? 'public';
1183
return match ($mode) {
1184
'public' => true,
1185
'elim_public' => $killed || $viewerId === $target,
1186
'known_target' => $viewerId === $target,
1187
'elim_known_target' => $killed && $viewerId === $target,
1188
default => true,
1189
};
1190
}
1191
1192
/**
1193
* Filter the stored event log for one viewer. Hidden events are omitted
1194
* entirely (no generic marker — a tick would leak that something happened).
1195
* Returns clones; the stored game is never mutated.
1196
*
1197
* @return list<array<string,mixed>>
1198
*/
1199
public static function filterEvents(array $game, string $viewerId): array
1200
{
1201
$out = [];
1202
foreach ($game['events'] ?? [] as $ev) {
1203
$f = self::filterEvent($game, $ev, $viewerId);
1204
if ($f !== null) {
1205
$out[] = $f;
1206
}
1207
}
1208
return $out;
1209
}
1210
1211
/**
1212
* @param array<string,mixed> $ev
1213
* @return array<string,mixed>|null
1214
*/
1215
public static function filterEvent(array $game, array $ev, string $viewerId): ?array
1216
{
1217
$rules = $game['rules'] ?? self::defaultRules();
1218
$type = $ev['type'] ?? '';
1219
$copy = $ev; // shallow copy; nested arrays are replaced when stripped
1220
1221
if ($type === 'shoot') {
1222
$shooter = (string) ($ev['player'] ?? '');
1223
$target = (string) ($ev['target'] ?? '');
1224
$killed = !empty($ev['killed']);
1225
if (!self::canSeeShot($rules, $viewerId, $shooter, $target, $killed)) {
1226
return null;
1227
}
1228
// Remaining lives belong to the target: only they (or public lives) may see them.
1229
$livesPublic = ($rules['vis_lives'] ?? 'public') === 'public' || $viewerId === $target;
1230
if (!$livesPublic) {
1231
unset($copy['lives_left']);
1232
}
1233
$copy['damage'] = (int) ($ev['damage'] ?? 1);
1234
// Loot is an AP amount: only the shooter (and public AP) may see it.
1235
if (isset($copy['loot']) && ($rules['vis_ap'] ?? 'public') !== 'public'
1236
&& $viewerId !== $shooter) {
1237
unset($copy['loot']);
1238
}
1239
return $copy;
1240
}
1241
1242
if ($type === 'give') {
1243
$giver = (string) ($ev['player'] ?? '');
1244
$recipient = (string) ($ev['target'] ?? '');
1245
$mode = $rules['vis_gifts'] ?? 'public';
1246
if ($viewerId === $giver || $mode === 'public') {
1247
return $copy;
1248
}
1249
if ($mode === 'known_recipient' && $viewerId === $recipient) {
1250
return $copy;
1251
}
1252
if ($mode === 'anonymous' && $viewerId === $recipient) {
1253
unset($copy['player']);
1254
$copy['anonymous'] = true;
1255
return $copy;
1256
}
1257
return null;
1258
}
1259
1260
if ($type === 'upgrade') {
1261
$who = (string) ($ev['player'] ?? '');
1262
if ($viewerId === $who) {
1263
return $copy;
1264
}
1265
$mode = $rules['vis_range'] ?? 'public';
1266
if ($mode === 'public') {
1267
return $copy;
1268
}
1269
if ($mode === 'hidden') {
1270
return null;
1271
}
1272
// known_in_range: visible iff the viewer may currently see that player's range.
1273
$subj = self::player($game, $who);
1274
if ($subj && self::viewerInRangeOf($game, $viewerId, $subj)) {
1275
return $copy;
1276
}
1277
return null;
1278
}
1279
1280
if ($type === 'death') {
1281
// Death (alive=false) is always public. Strip "by" if the eliminating
1282
// shot is not visible to this viewer, so the killer is not leaked.
1283
$cause = $ev['cause'] ?? '';
1284
if ($cause === 'shot' && isset($ev['by'])) {
1285
$killer = (string) $ev['by'];
1286
$victim = (string) ($ev['player'] ?? '');
1287
if (!self::canSeeShot($rules, $viewerId, $killer, $victim, true)) {
1288
unset($copy['by']);
1289
}
1290
if (isset($copy['loot']) && ($rules['vis_ap'] ?? 'public') !== 'public'
1291
&& $viewerId !== $killer) {
1292
unset($copy['loot']);
1293
}
1294
}
1295
return $copy;
1296
}
1297
1298
if ($type === 'daily') {
1299
$mode = $rules['vis_ap'] ?? 'public';
1300
if ($mode === 'hidden') {
1301
$grants = $ev['grants'] ?? [];
1302
if (is_array($grants)) {
1303
$copy['grants'] = array_key_exists($viewerId, $grants)
1304
? [$viewerId => $grants[$viewerId]]
1305
: [];
1306
}
1307
}
1308
// Jury winners stay public (the announced result). Vote counts, if
1309
// present, are not needed by the client; strip to keep votes secret.
1310
if (isset($copy['jury']) && is_array($copy['jury'])) {
1311
$jury = $copy['jury'];
1312
unset($jury['counts']);
1313
$copy['jury'] = $jury;
1314
}
1315
return $copy;
1316
}
1317
1318
if ($type === 'shrink') {
1319
// Movement in the report is public. The explicit "hurt" list leaks
1320
// a life loss when lives are hidden — keep only the viewer's own id.
1321
if (($rules['vis_lives'] ?? 'public') !== 'public') {
1322
$hurt = $ev['hurt'] ?? [];
1323
$copy['hurt'] = array_values(array_filter(
1324
is_array($hurt) ? $hurt : [],
1325
fn ($id) => $id === $viewerId
1326
));
1327
}
1328
return $copy;
1329
}
1330
1331
// move, start, surrender, win, draw, shrink deaths: always visible.
1332
return $copy;
1333
}
1334
1335
public static function present(array $game, string $viewerId, ?int $now = null): array
1336
{
1337
$now = $now ?? self::now();
1338
$legal = $game['status'] === 'running' ? self::legal($game, $viewerId, $now) : [
1339
'move' => [], 'shoot' => [], 'give' => [], 'upgrade' => false,
1340
'surrender' => false, 'vote' => null, 'my_vote' => null,
1341
];
1342
$players = [];
1343
foreach ($game['players'] as $p) {
1344
$noteKey = $viewerId . "\0" . $p['id'];
1345
$players[] = self::presentPlayer($game, $p, $viewerId, $noteKey);
1346
}
1347
$messages = [];
1348
foreach ($game['messages'] as $m) {
1349
if ($m['from'] === $viewerId || $m['to'] === $viewerId) {
1350
$messages[] = $m;
1351
}
1352
}
1353
$events = self::filterEvents($game, $viewerId);
1354
$shrinkIn = self::daysUntilShrink($game);
1355
return [
1356
'id' => $game['id'],
1357
'code' => $game['code'],
1358
'host_id' => $game['host_id'],
1359
'status' => $game['status'],
1360
'created_at' => $game['created_at'],
1361
'started_at' => $game['started_at'],
1362
'finished_at' => $game['finished_at'],
1363
'rules' => $game['rules'],
1364
'grid' => (int) $game['grid'],
1365
'day' => (int) $game['day'],
1366
'next_distribution_at' => $game['next_distribution_at'],
1367
'arena_inset' => (int) $game['arena_inset'],
1368
'max_inset' => self::maxInset((int) $game['grid']),
1369
'shrink_in_days' => $shrinkIn,
1370
'winner_id' => $game['winner_id'],
1371
'draw' => !empty($game['draw']),
1372
'players' => $players,
1373
'events' => $events,
1374
'messages' => $messages,
1375
'legal' => $legal,
1376
'you' => $viewerId,
1377
'timezone' => self::TZ,
1378
'version' => (int) ($game['version'] ?? $game['event_seq'] ?? 0),
1379
'server_now' => $now,
1380
'ceasefire' => self::ceasefireInfo($game, $now),
1381
];
1382
}
1383
1384
public static function lobbyView(array $game, string $viewerId): array
1385
{
1386
$players = [];
1387
foreach ($game['players'] as $p) {
1388
$players[] = [
1389
'id' => $p['id'],
1390
'name' => $p['name'],
1391
'avatar' => $p['avatar'],
1392
'color' => $p['color'],
1393
'is_you' => $p['id'] === $viewerId,
1394
'is_host' => $p['id'] === $game['host_id'],
1395
];
1396
}
1397
return [
1398
'id' => $game['id'],
1399
'code' => $game['code'],
1400
'host_id' => $game['host_id'],
1401
'status' => $game['status'],
1402
'created_at' => $game['created_at'],
1403
'rules' => $game['rules'],
1404
'players' => $players,
1405
'can_start' => $game['status'] === 'lobby'
1406
&& $game['host_id'] === $viewerId
1407
&& count($game['players']) >= self::MIN_PLAYERS,
1408
'you' => $viewerId,
1409
'timezone' => self::TZ,
1410
];
1411
}
1412
1413
public static function asBool(mixed $v): bool
1414
{
1415
if (is_bool($v)) {
1416
return $v;
1417
}
1418
if (is_int($v) || is_float($v)) {
1419
return $v != 0;
1420
}
1421
if (!is_string($v)) {
1422
return (bool) $v;
1423
}
1424
$s = strtolower(trim($v));
1425
return !in_array($s, ['', '0', 'false', 'off', 'no', 'null'], true);
1426
}
1427
1428
/**
1429
* Normalise "HH:MM"-"HH:MM" ranges. Invalid entries are dropped.
1430
* A range may wrap midnight (start > end). Zero-length (start==end) is dropped.
1431
*
1432
* @param mixed $raw
1433
* @return list<array{start:string,end:string}>
1434
*/
1435
public static function normalizeRanges(mixed $raw): array
1436
{
1437
if (!is_array($raw)) {
1438
return [];
1439
}
1440
$out = [];
1441
$seen = [];
1442
foreach ($raw as $r) {
1443
if (!is_array($r)) {
1444
continue;
1445
}
1446
$start = self::parseHm($r['start'] ?? $r[0] ?? null);
1447
$end = self::parseHm($r['end'] ?? $r[1] ?? null);
1448
if ($start === null || $end === null || $start === $end) {
1449
continue;
1450
}
1451
$key = $start . '-' . $end;
1452
if (isset($seen[$key])) {
1453
continue;
1454
}
1455
$seen[$key] = true;
1456
$out[] = ['start' => $start, 'end' => $end];
1457
}
1458
usort($out, fn ($a, $b) => strcmp($a['start'], $b['start']));
1459
return array_slice($out, 0, 12);
1460
}
1461
1462
/** @return string|null "HH:MM" */
1463
public static function parseHm(mixed $v): ?string
1464
{
1465
if (is_int($v)) {
1466
if ($v < 0 || $v > 23 * 60 + 59) {
1467
return null;
1468
}
1469
return sprintf('%02d:%02d', intdiv($v, 60), $v % 60);
1470
}
1471
if (!is_string($v)) {
1472
return null;
1473
}
1474
$v = trim($v);
1475
if (!preg_match('/^(\d{1,2}):(\d{2})$/', $v, $m)) {
1476
return null;
1477
}
1478
$h = (int) $m[1];
1479
$min = (int) $m[2];
1480
if ($h > 23 || $min > 59) {
1481
return null;
1482
}
1483
return sprintf('%02d:%02d', $h, $min);
1484
}
1485
1486
public static function hmToMinutes(string $hm): int
1487
{
1488
[$h, $m] = array_map('intval', explode(':', $hm));
1489
return $h * 60 + $m;
1490
}
1491
1492
/**
1493
* Convert a local Europe/Amsterdam wall-clock on a calendar date to unix.
1494
* Uses midnight + hours/minutes so DST spring-forward skips and
1495
* fall-back uses PHP's first occurrence, then addition continues correctly.
1496
*/
1497
public static function amsterdamWallclock(string $ymd, string $hm): int
1498
{
1499
$tz = new DateTimeZone(self::TZ);
1500
$dt = new DateTime($ymd . ' 00:00:00', $tz);
1501
$mins = self::hmToMinutes($hm);
1502
if ($mins > 0) {
1503
$dt->modify('+' . $mins . ' minutes');
1504
}
1505
return $dt->getTimestamp();
1506
}
1507
1508
/**
1509
* Merged cease-fire intervals as [start_ts, end_ts] covering yesterday
1510
* through two days ahead, so midnight wraps and DST are exact.
1511
*
1512
* @return list<array{0:int,1:int}>
1513
*/
1514
public static function ceasefireIntervals(array $ranges, int $now): array
1515
{
1516
if ($ranges === []) {
1517
return [];
1518
}
1519
$tz = new DateTimeZone(self::TZ);
1520
$anchor = (new DateTime('@' . $now))->setTimezone($tz);
1521
$intervals = [];
1522
for ($d = -1; $d <= 3; $d++) {
1523
$day = (clone $anchor)->modify(($d >= 0 ? '+' : '') . $d . ' day');
1524
$ymd = $day->format('Y-m-d');
1525
$next = (clone $day)->modify('+1 day')->format('Y-m-d');
1526
foreach ($ranges as $r) {
1527
$startM = self::hmToMinutes($r['start']);
1528
$endM = self::hmToMinutes($r['end']);
1529
$startTs = self::amsterdamWallclock($ymd, $r['start']);
1530
if ($endM > $startM) {
1531
$endTs = self::amsterdamWallclock($ymd, $r['end']);
1532
} else {
1533
// Wraps midnight: ends on the next calendar day.
1534
$endTs = self::amsterdamWallclock($next, $r['end']);
1535
}
1536
if ($endTs > $startTs) {
1537
$intervals[] = [$startTs, $endTs];
1538
}
1539
}
1540
}
1541
if ($intervals === []) {
1542
return [];
1543
}
1544
usort($intervals, fn ($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);
1545
$merged = [];
1546
foreach ($intervals as $iv) {
1547
if ($merged === [] || $iv[0] > $merged[count($merged) - 1][1]) {
1548
$merged[] = $iv;
1549
} else {
1550
$merged[count($merged) - 1][1] = max($merged[count($merged) - 1][1], $iv[1]);
1551
}
1552
}
1553
return $merged;
1554
}
1555
1556
public static function ceasefireActive(array $game, int $now): bool
1557
{
1558
$info = self::ceasefireInfo($game, $now);
1559
return $info !== null && !empty($info['active']);
1560
}
1561
1562
/**
1563
* @return array{enabled:bool,active:bool,until:?int,seconds:int}|null
1564
* null when the rule is off or there are no ranges.
1565
*/
1566
public static function ceasefireInfo(array $game, int $now): ?array
1567
{
1568
$rules = $game['rules'] ?? [];
1569
if (empty($rules['ceasefire'])) {
1570
return null;
1571
}
1572
$ranges = self::normalizeRanges($rules['ceasefire_ranges'] ?? []);
1573
if ($ranges === []) {
1574
return null;
1575
}
1576
$intervals = self::ceasefireIntervals($ranges, $now);
1577
$active = false;
1578
$until = null;
1579
foreach ($intervals as $iv) {
1580
if ($now >= $iv[0] && $now < $iv[1]) {
1581
$active = true;
1582
$until = $iv[1];
1583
break;
1584
}
1585
if ($iv[0] > $now && ($until === null || $iv[0] < $until)) {
1586
$until = $iv[0];
1587
}
1588
}
1589
$seconds = $until !== null ? max(0, $until - $now) : 0;
1590
return [
1591
'enabled' => true,
1592
'active' => $active,
1593
'until' => $until,
1594
'seconds' => $seconds,
1595
'ranges' => $ranges,
1596
];
1597
}
1598
1599
public static function generateCode(): string
1600
{
1601
// Crockford-ish, no 0/O/I/1/L.
1602
$alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
1603
$len = strlen($alphabet);
1604
$code = '';
1605
for ($i = 0; $i < self::CODE_LEN; $i++) {
1606
$code .= $alphabet[random_int(0, $len - 1)];
1607
}
1608
return $code;
1609
}
1610
1611
public static function generateId(): string
1612
{
1613
return bin2hex(random_bytes(12));
1614
}
1615
}
@@ -0,0 +1,1615 @@1
<?php2
declare(strict_types=1);3
4
/**5
* Pure, deterministic Allianties rule engine.6
* Server and tests share this. The client replays the same event log.7
*8
* Extra rules (jury, shrinking arena, and future ones) are toggles on the9
* game's `rules` object and are applied only from here, so they can be10
* turned on or off without touching the rest of the stack.11
*/12
final class Engine13
{14
public const TZ = 'Europe/Amsterdam';15
public const STARTING_LIVES = 3;16
public const STARTING_RANGE = 2;17
public const STARTING_AP = 1;18
public const MIN_PLAYERS = 2;19
public const MAX_PLAYERS = 16;20
public const MIN_GRID = 6;21
public const MIN_ARENA = 3;22
public const DEFAULT_SHRINK_DAYS = 7;23
public const MIN_SHRINK_DAYS = 1;24
public const MAX_SHRINK_DAYS = 30;25
public const NOTE_MAX = 2000;26
public const CHAT_MAX = 1000;27
public const NAME_MAX = 64;28
public const CODE_LEN = 6;29
30
/** @var list<string> Allowed vis_shots values; first is the default. */31
public const VIS_SHOTS = ['public', 'elim_public', 'known_target', 'elim_known_target'];32
/** @var list<string> */33
public const VIS_GIFTS = ['public', 'known_recipient', 'anonymous'];34
/** @var list<string> */35
public const VIS_AP = ['public', 'hidden'];36
/** @var list<string> */37
public const VIS_RANGE = ['public', 'known_in_range', 'hidden'];38
/** @var list<string> */39
public const VIS_LIVES = ['public', 'hidden'];40
41
/** @var list<string> */42
public const COLORS = [43
'#e74c3c', '#3498db', '#2ecc71', '#f1c40f',44
'#9b59b6', '#e67e22', '#1abc9c', '#e91e63',45
'#00bcd4', '#8bc34a', '#ff5722', '#3f51b5',46
'#795548', '#607d8b', '#cddc39', '#ff9800',47
];48
49
/** Injected unix timestamp for tests; null means time(). */50
public static ?int $now = null;51
52
public static function now(): int53
{54
return self::$now ?? time();55
}56
57
public static function defaultRules(): array58
{59
return [60
'jury' => true,61
'shrinking_arena' => false,62
'shrink_interval_days' => self::DEFAULT_SHRINK_DAYS,63
'ceasefire' => false,64
'ceasefire_ranges' => [],65
'ap_loot' => false,66
'ap_time' => '00:00',67
'vis_shots' => 'public',68
'vis_gifts' => 'public',69
'vis_ap' => 'public',70
'vis_range' => 'public',71
'vis_lives' => 'public',72
];73
}74
75
public static function normalizeRules(array $raw): array76
{77
$d = self::defaultRules();78
$d['jury'] = array_key_exists('jury', $raw) ? (bool) $raw['jury'] : true;79
$d['shrinking_arena'] = !empty($raw['shrinking_arena']);80
$n = isset($raw['shrink_interval_days']) ? (int) $raw['shrink_interval_days'] : self::DEFAULT_SHRINK_DAYS;81
if ($n < self::MIN_SHRINK_DAYS) {82
$n = self::MIN_SHRINK_DAYS;83
}84
if ($n > self::MAX_SHRINK_DAYS) {85
$n = self::MAX_SHRINK_DAYS;86
}87
$d['shrink_interval_days'] = $n;88
$d['ceasefire'] = self::asBool($raw['ceasefire'] ?? false);89
$d['ceasefire_ranges'] = self::normalizeRanges($raw['ceasefire_ranges'] ?? []);90
$d['ap_loot'] = self::asBool($raw['ap_loot'] ?? false);91
$hm = self::parseHm($raw['ap_time'] ?? '00:00');92
$d['ap_time'] = $hm ?? '00:00';93
$d['vis_shots'] = self::visChoice($raw['vis_shots'] ?? null, self::VIS_SHOTS, 'public');94
$d['vis_gifts'] = self::visChoice($raw['vis_gifts'] ?? null, self::VIS_GIFTS, 'public');95
$d['vis_ap'] = self::visChoice($raw['vis_ap'] ?? null, self::VIS_AP, 'public');96
$d['vis_range'] = self::visChoice($raw['vis_range'] ?? null, self::VIS_RANGE, 'public');97
$d['vis_lives'] = self::visChoice($raw['vis_lives'] ?? null, self::VIS_LIVES, 'public');98
return $d;99
}100
101
/** Square board: at least 6, about 6 tiles of space per player. */102
public static function gridSize(int $n): int103
{104
if ($n < 1) {105
$n = 1;106
}107
return max(self::MIN_GRID, (int) ceil(sqrt($n * 6)));108
}109
110
/** Largest inset that still leaves a MIN_ARENA playable square. */111
public static function maxInset(int $size): int112
{113
return max(0, (int) floor(($size - self::MIN_ARENA) / 2));114
}115
116
/**117
* Place players evenly on a ring around the centre, on unique tiles,118
* starting at the top and going clockwise. Never on the same tile.119
*120
* @return list<array{x:int,y:int}>121
*/122
public static function startingPositions(int $n, int $size): array123
{124
if ($n < 1) {125
return [];126
}127
$cx = ($size - 1) / 2.0;128
$cy = ($size - 1) / 2.0;129
$radius = max(1.0, ($size - 1) / 2.0 - 1.0);130
$used = [];131
$out = [];132
for ($i = 0; $i < $n; $i++) {133
$ang = -M_PI / 2 + ($i * 2 * M_PI / $n);134
$fx = $cx + $radius * cos($ang);135
$fy = $cy + $radius * sin($ang);136
$x = (int) max(0, min($size - 1, (int) round($fx)));137
$y = (int) max(0, min($size - 1, (int) round($fy)));138
$key = $x . ',' . $y;139
if (isset($used[$key])) {140
$found = false;141
for ($d = 1; $d < $size * 2 && !$found; $d++) {142
for ($dx = -$d; $dx <= $d && !$found; $dx++) {143
for ($dy = -$d; $dy <= $d; $dy++) {144
if (max(abs($dx), abs($dy)) !== $d) {145
continue;146
}147
$nx = $x + $dx;148
$ny = $y + $dy;149
if ($nx < 0 || $ny < 0 || $nx >= $size || $ny >= $size) {150
continue;151
}152
$k2 = $nx . ',' . $ny;153
if (!isset($used[$k2])) {154
$x = $nx;155
$y = $ny;156
$key = $k2;157
$found = true;158
break;159
}160
}161
}162
}163
}164
$used[$key] = true;165
$out[] = ['x' => $x, 'y' => $y];166
}167
return $out;168
}169
170
public static function chebyshev(int $x1, int $y1, int $x2, int $y2): int171
{172
return max(abs($x1 - $x2), abs($y1 - $y2));173
}174
175
public static function inBounds(int $size, int $x, int $y): bool176
{177
return $x >= 0 && $y >= 0 && $x < $size && $y < $size;178
}179
180
public static function isPassable(int $size, int $inset, int $x, int $y): bool181
{182
if (!self::inBounds($size, $x, $y)) {183
return false;184
}185
return $x >= $inset && $y >= $inset && $x < $size - $inset && $y < $size - $inset;186
}187
188
/**189
* Next occurrence of a Europe/Amsterdam wall-clock time strictly after $from.190
* Used for the per-lobby daily AP time (default 00:00).191
* If that clock time is skipped by a spring-forward DST gap, PHP's192
* DateTime::setTime lands on the first valid instant after the gap.193
*/194
public static function nextDistribution(int $from, ?string $hm = null): int195
{196
$hm = self::parseHm($hm ?? '00:00') ?? '00:00';197
[$h, $min] = array_map('intval', explode(':', $hm));198
$tz = new DateTimeZone(self::TZ);199
$dt = (new DateTime('@' . $from))->setTimezone($tz);200
$candidate = clone $dt;201
$candidate->setTime($h, $min, 0);202
if ($candidate->getTimestamp() <= $from) {203
$candidate->modify('+1 day');204
$candidate->setTime($h, $min, 0);205
}206
return $candidate->getTimestamp();207
}208
209
/** Next 00:00 Europe/Amsterdam strictly after $from. */210
public static function nextMidnight(int $from): int211
{212
return self::nextDistribution($from, '00:00');213
}214
215
/** Today's 00:00 Amsterdam on or before $from. */216
public static function thisMidnight(int $from): int217
{218
$tz = new DateTimeZone(self::TZ);219
$dt = new DateTime('@' . $from);220
$dt->setTimezone($tz);221
$dt->setTime(0, 0, 0);222
return $dt->getTimestamp();223
}224
225
/**226
* A new lobby (status=lobby) with the host as first member.227
*/228
public static function newLobby(229
string $id,230
string $code,231
string $hostId,232
string $hostName,233
?string $avatar,234
array $rules,235
int $now236
): array {237
$rules = self::normalizeRules($rules);238
return [239
'id' => $id,240
'code' => $code,241
'host_id' => $hostId,242
'status' => 'lobby',243
'created_at' => $now,244
'started_at' => null,245
'finished_at' => null,246
'rules' => $rules,247
'grid' => self::MIN_GRID,248
'day' => 0,249
'next_distribution_at' => null,250
'arena_inset' => 0,251
'winner_id' => null,252
'draw' => false,253
'players' => [254
self::newPlayer($hostId, $hostName, $avatar, 0, $now),255
],256
'events' => [],257
'votes' => [],258
'notes' => [],259
'messages' => [],260
'event_seq' => 0,261
'version' => 1,262
];263
}264
265
public static function newPlayer(string $id, string $name, ?string $avatar, int $colorIndex, int $now): array266
{267
$colors = self::COLORS;268
$color = $colors[$colorIndex % count($colors)];269
return [270
'id' => $id,271
'name' => $name,272
'avatar' => $avatar,273
'color' => $color,274
'color_index' => $colorIndex,275
'x' => 0,276
'y' => 0,277
'lives' => self::STARTING_LIVES,278
'ap' => 0,279
'range' => self::STARTING_RANGE,280
'alive' => true,281
'surrendered' => false,282
'joined_at' => $now,283
];284
}285
286
public static function playerIndex(array $game, string $userId): ?int287
{288
foreach ($game['players'] as $i => $p) {289
if ($p['id'] === $userId) {290
return (int) $i;291
}292
}293
return null;294
}295
296
public static function player(array $game, string $userId): ?array297
{298
$i = self::playerIndex($game, $userId);299
return $i === null ? null : $game['players'][$i];300
}301
302
/** @return list<array> */303
public static function living(array $game): array304
{305
return array_values(array_filter($game['players'], fn ($p) => !empty($p['alive'])));306
}307
308
public static function occupiedByLiving(array $game, int $x, int $y, ?string $except = null): ?string309
{310
foreach ($game['players'] as $p) {311
if (empty($p['alive'])) {312
continue;313
}314
if ($except !== null && $p['id'] === $except) {315
continue;316
}317
if ((int) $p['x'] === $x && (int) $p['y'] === $y) {318
return $p['id'];319
}320
}321
return null;322
}323
324
public static function pushEvent(array &$game, string $type, array $data, int $now): array325
{326
$game['event_seq'] = (int) ($game['event_seq'] ?? 0) + 1;327
$game['version'] = (int) ($game['version'] ?? 0) + 1;328
$ev = array_merge([329
'id' => $game['event_seq'],330
't' => $now,331
'type' => $type,332
], $data);333
$game['events'][] = $ev;334
return $ev;335
}336
337
/**338
* Join a lobby. Throws RuntimeException with a stable error code.339
*/340
public static function join(array $game, string $userId, string $name, ?string $avatar, int $now): array341
{342
if ($game['status'] !== 'lobby') {343
throw new RuntimeException('game_started');344
}345
if (self::playerIndex($game, $userId) !== null) {346
return $game; // already in347
}348
if (count($game['players']) >= self::MAX_PLAYERS) {349
throw new RuntimeException('lobby_full');350
}351
$game['players'][] = self::newPlayer($userId, $name, $avatar, count($game['players']), $now);352
return $game;353
}354
355
public static function leaveLobby(array $game, string $userId, int $now): ?array356
{357
if ($game['status'] !== 'lobby') {358
throw new RuntimeException('game_started');359
}360
$idx = self::playerIndex($game, $userId);361
if ($idx === null) {362
return $game;363
}364
array_splice($game['players'], $idx, 1);365
if (count($game['players']) === 0) {366
return null; // delete lobby367
}368
// Re-index colours; if host left, earliest joiner becomes host.369
foreach ($game['players'] as $i => &$p) {370
$p['color_index'] = $i;371
$p['color'] = self::COLORS[$i % count(self::COLORS)];372
}373
unset($p);374
if ($game['host_id'] === $userId) {375
$game['host_id'] = $game['players'][0]['id'];376
}377
return $game;378
}379
380
public static function setLobbyRules(array $game, string $userId, array $rules): array381
{382
if ($game['status'] !== 'lobby') {383
throw new RuntimeException('game_started');384
}385
if ($game['host_id'] !== $userId) {386
throw new RuntimeException('not_host');387
}388
$game['rules'] = self::normalizeRules(array_merge($game['rules'], $rules));389
return $game;390
}391
392
public static function start(array $game, string $userId, int $now): array393
{394
if ($game['status'] !== 'lobby') {395
throw new RuntimeException('game_started');396
}397
if ($game['host_id'] !== $userId) {398
throw new RuntimeException('not_host');399
}400
$n = count($game['players']);401
if ($n < self::MIN_PLAYERS) {402
throw new RuntimeException('min_players');403
}404
$size = self::gridSize($n);405
$pos = self::startingPositions($n, $size);406
$game['grid'] = $size;407
$game['status'] = 'running';408
$game['started_at'] = $now;409
$game['day'] = 0;410
$game['arena_inset'] = 0;411
$game['next_distribution_at'] = self::nextDistribution($now, $game['rules']['ap_time'] ?? '00:00');412
$placed = [];413
foreach ($game['players'] as $i => &$p) {414
$p['x'] = $pos[$i]['x'];415
$p['y'] = $pos[$i]['y'];416
$p['lives'] = self::STARTING_LIVES;417
$p['ap'] = self::STARTING_AP;418
$p['range'] = self::STARTING_RANGE;419
$p['alive'] = true;420
$p['surrendered'] = false;421
$placed[] = [422
'id' => $p['id'],423
'x' => $p['x'],424
'y' => $p['y'],425
'color' => $p['color'],426
'name' => $p['name'],427
];428
}429
unset($p);430
self::pushEvent($game, 'start', [431
'grid' => $size,432
'players' => $placed,433
'rules' => $game['rules'],434
'spend' => false,435
], $now);436
return $game;437
}438
439
/**440
* Catch up daily distributions (AP, jury, shrink) until $now.441
* Safe to call on every request.442
*/443
public static function applyDue(array $game, int $now): array444
{445
if ($game['status'] !== 'running') {446
return $game;447
}448
$guard = 0;449
while (450
isset($game['next_distribution_at'])451
&& $game['next_distribution_at'] !== null452
&& (int) $game['next_distribution_at'] <= $now453
&& $game['status'] === 'running'454
&& $guard < 4000455
) {456
$at = (int) $game['next_distribution_at'];457
$game = self::distributeOneDay($game, $at);458
$game['next_distribution_at'] = self::nextDistribution($at, $game['rules']['ap_time'] ?? '00:00');459
$guard++;460
}461
return $game;462
}463
464
public static function daysUntilShrink(array $game): ?int465
{466
if ($game['status'] !== 'running' || empty($game['rules']['shrinking_arena'])) {467
return null;468
}469
$size = (int) $game['grid'];470
if ((int) $game['arena_inset'] >= self::maxInset($size)) {471
return null;472
}473
$interval = (int) $game['rules']['shrink_interval_days'];474
$day = (int) $game['day'];475
// Next shrink at day = k*interval for k>=1, i.e. after `interval` midnights.476
$nextAt = (int) (ceil(($day + 1) / $interval) * $interval);477
if ($nextAt <= $day) {478
$nextAt += $interval;479
}480
return $nextAt - $day;481
}482
483
private static function distributeOneDay(array $game, int $at): array484
{485
$game['day'] = (int) $game['day'] + 1;486
$day = (int) $game['day'];487
$grants = [];488
$jury = null;489
490
// 1. Shrink first so someone who dies today does not receive AP.491
$shrink = null;492
if (!empty($game['rules']['shrinking_arena'])) {493
$interval = (int) $game['rules']['shrink_interval_days'];494
$size = (int) $game['grid'];495
$inset = (int) $game['arena_inset'];496
if ($interval > 0 && $day % $interval === 0 && $inset < self::maxInset($size)) {497
$result = self::applyShrink($game, $at);498
$game = $result['game'];499
$shrink = $result['report'];500
}501
}502
503
if ($game['status'] !== 'running') {504
// Finished mid-shrink; still record the day event.505
self::pushEvent($game, 'daily', [506
'day' => $day,507
'grants' => $grants,508
'jury' => $jury,509
'shrink' => $shrink,510
'spend' => false,511
], $at);512
return $game;513
}514
515
// 2. Jury: unique or tied living targets each get +1. Votes stay secret.516
if (!empty($game['rules']['jury'])) {517
$jury = self::tallyJury($game);518
}519
520
// 3. Grant 1 AP to every living player, plus jury bonus.521
foreach ($game['players'] as &$p) {522
if (empty($p['alive'])) {523
continue;524
}525
$add = 1;526
if ($jury && in_array($p['id'], $jury['winners'], true)) {527
$add += 1;528
}529
$p['ap'] = (int) $p['ap'] + $add;530
$grants[$p['id']] = $add;531
}532
unset($p);533
534
// Votes reset for the new day (changeable until the next distribution).535
$game['votes'] = [];536
537
self::pushEvent($game, 'daily', [538
'day' => $day,539
'grants' => $grants,540
'jury' => $jury,541
'shrink' => $shrink,542
'spend' => false,543
], $at);544
545
$game = self::checkEnd($game, $at);546
return $game;547
}548
549
/**550
* Tally current votes. Winners are living players with the strictly551
* highest count; on a tie every tied player is a winner (each +1 AP).552
* Players with zero votes never win, even if nobody voted (no award).553
*554
* @return array{winners:list<string>,counts:array<string,int>,votes_cast:int}|null555
*/556
public static function tallyJury(array $game): ?array557
{558
$livingIds = [];559
foreach (self::living($game) as $p) {560
$livingIds[$p['id']] = true;561
}562
$counts = [];563
$cast = 0;564
foreach ($game['votes'] as $voter => $target) {565
if (!is_string($voter) || !is_string($target)) {566
continue;567
}568
if (!isset($livingIds[$target])) {569
continue;570
}571
// Voter should be a dead participant.572
$v = self::player($game, $voter);573
if (!$v || !empty($v['alive'])) {574
continue;575
}576
$counts[$target] = ($counts[$target] ?? 0) + 1;577
$cast++;578
}579
if ($cast === 0 || $counts === []) {580
return ['winners' => [], 'counts' => $counts, 'votes_cast' => 0];581
}582
$max = max($counts);583
$winners = [];584
foreach ($counts as $id => $c) {585
if ($c === $max) {586
$winners[] = $id;587
}588
}589
sort($winners);590
return ['winners' => $winners, 'counts' => $counts, 'votes_cast' => $cast];591
}592
593
/**594
* Advance arena_inset by 1. Players on the new outer ring lose 1 life595
* and, if still alive, are pushed to the nearest free passable tile.596
*597
* @return array{game:array,report:array}598
*/599
public static function applyShrink(array $game, int $now): array600
{601
$size = (int) $game['grid'];602
$newInset = (int) $game['arena_inset'] + 1;603
if ($newInset > self::maxInset($size)) {604
return ['game' => $game, 'report' => null];605
}606
$game['arena_inset'] = $newInset;607
$moved = [];608
$hurt = [];609
$killed = [];610
$crushed = [];611
612
// Deterministic order: by player id.613
$indices = [];614
foreach ($game['players'] as $i => $p) {615
$indices[] = $i;616
}617
usort($indices, function ($a, $b) use ($game) {618
return strcmp($game['players'][$a]['id'], $game['players'][$b]['id']);619
});620
621
foreach ($indices as $i) {622
$p = $game['players'][$i];623
if (empty($p['alive'])) {624
continue;625
}626
$x = (int) $p['x'];627
$y = (int) $p['y'];628
if (self::isPassable($size, $newInset, $x, $y)) {629
continue;630
}631
// Standing on the new ring: take 1 damage.632
$p['lives'] = (int) $p['lives'] - 1;633
$hurt[] = $p['id'];634
if ($p['lives'] <= 0) {635
$p['lives'] = 0;636
$p['alive'] = false;637
$p['ap'] = 0;638
$killed[] = $p['id'];639
$game['players'][$i] = $p;640
self::pushEvent($game, 'death', [641
'player' => $p['id'],642
'cause' => 'shrink',643
'spend' => false,644
], $now);645
continue;646
}647
$dest = self::nearestFreeTile($game, $size, $newInset, $x, $y, $p['id']);648
if ($dest === null) {649
// No free inward tile: crushed, eliminated.650
$p['lives'] = 0;651
$p['alive'] = false;652
$p['ap'] = 0;653
$killed[] = $p['id'];654
$crushed[] = $p['id'];655
$game['players'][$i] = $p;656
self::pushEvent($game, 'death', [657
'player' => $p['id'],658
'cause' => 'crushed',659
'spend' => false,660
], $now);661
continue;662
}663
$from = ['x' => $x, 'y' => $y];664
$p['x'] = $dest['x'];665
$p['y'] = $dest['y'];666
$moved[] = ['id' => $p['id'], 'from' => $from, 'to' => $dest];667
$game['players'][$i] = $p;668
}669
670
$report = [671
'inset' => $newInset,672
'hurt' => $hurt,673
'killed' => $killed,674
'crushed' => $crushed,675
'moved' => $moved,676
];677
self::pushEvent($game, 'shrink', array_merge($report, ['spend' => false]), $now);678
$game = self::checkEnd($game, $now);679
return ['game' => $game, 'report' => $report];680
}681
682
/**683
* Nearest free passable tile, Chebyshev first, then Euclidean to centre,684
* then (y, x) for a stable leftover tie.685
*686
* @return array{x:int,y:int}|null687
*/688
public static function nearestFreeTile(689
array $game,690
int $size,691
int $inset,692
int $fromX,693
int $fromY,694
string $moverId695
): ?array {696
$cx = ($size - 1) / 2.0;697
$cy = ($size - 1) / 2.0;698
$best = null;699
$bestKey = null;700
for ($x = $inset; $x < $size - $inset; $x++) {701
for ($y = $inset; $y < $size - $inset; $y++) {702
if (self::occupiedByLiving($game, $x, $y, $moverId) !== null) {703
continue;704
}705
$d = self::chebyshev($fromX, $fromY, $x, $y);706
$dc = ($x - $cx) * ($x - $cx) + ($y - $cy) * ($y - $cy);707
$key = sprintf('%04d-%012.6f-%04d-%04d', $d, $dc, $y, $x);708
if ($bestKey === null || $key < $bestKey) {709
$bestKey = $key;710
$best = ['x' => $x, 'y' => $y];711
}712
}713
}714
return $best;715
}716
717
public static function checkEnd(array $game, int $now): array718
{719
if ($game['status'] !== 'running') {720
return $game;721
}722
$alive = self::living($game);723
if (count($alive) === 1) {724
$game['status'] = 'finished';725
$game['finished_at'] = $now;726
$game['winner_id'] = $alive[0]['id'];727
$game['draw'] = false;728
self::pushEvent($game, 'win', [729
'player' => $alive[0]['id'],730
'spend' => false,731
], $now);732
} elseif (count($alive) === 0) {733
$game['status'] = 'finished';734
$game['finished_at'] = $now;735
$game['winner_id'] = null;736
$game['draw'] = true;737
self::pushEvent($game, 'draw', ['spend' => false], $now);738
}739
return $game;740
}741
742
/**743
* Legal actions for a viewer (after applyDue).744
*745
* @return array{746
* move:list<array{x:int,y:int}>,747
* shoot:list<string>,748
* give:list<string>,749
* upgrade:bool,750
* surrender:bool,751
* vote:list<string>|null,752
* my_vote:?string753
* }754
*/755
public static function legal(array $game, string $userId, ?int $now = null): array756
{757
$now = $now ?? self::now();758
759
$empty = [760
'move' => [],761
'shoot' => [],762
'give' => [],763
'upgrade' => false,764
'surrender' => false,765
'vote' => null,766
'my_vote' => null,767
'ceasefire' => false,768
];769
if ($game['status'] !== 'running') {770
return $empty;771
}772
$me = self::player($game, $userId);773
if (!$me) {774
return $empty;775
}776
$size = (int) $game['grid'];777
$inset = (int) $game['arena_inset'];778
if (empty($me['alive'])) {779
$vote = null;780
$myVote = null;781
if (!empty($game['rules']['jury'])) {782
$vote = [];783
foreach (self::living($game) as $p) {784
$vote[] = $p['id'];785
}786
$v = $game['votes'][$userId] ?? null;787
$myVote = is_string($v) ? $v : null;788
}789
$empty['vote'] = $vote;790
$empty['my_vote'] = $myVote;791
return $empty;792
}793
$empty['surrender'] = true;794
if ((int) $me['ap'] < 1) {795
return $empty;796
}797
// Moves: 8 neighbours.798
for ($dx = -1; $dx <= 1; $dx++) {799
for ($dy = -1; $dy <= 1; $dy++) {800
if ($dx === 0 && $dy === 0) {801
continue;802
}803
$x = (int) $me['x'] + $dx;804
$y = (int) $me['y'] + $dy;805
if (!self::isPassable($size, $inset, $x, $y)) {806
continue;807
}808
if (self::occupiedByLiving($game, $x, $y, $userId) !== null) {809
continue;810
}811
$empty['move'][] = ['x' => $x, 'y' => $y];812
}813
}814
$range = (int) $me['range'];815
foreach ($game['players'] as $p) {816
if ($p['id'] === $userId || empty($p['alive'])) {817
continue;818
}819
$d = self::chebyshev((int) $me['x'], (int) $me['y'], (int) $p['x'], (int) $p['y']);820
if ($d <= $range) {821
$empty['shoot'][] = $p['id'];822
$empty['give'][] = $p['id'];823
}824
}825
// Upgrade: cap at the board's max Chebyshev distance (covers the board).826
$maxRange = max(1, $size - 1);827
$empty['upgrade'] = (int) $me['range'] < $maxRange;828
if (self::ceasefireActive($game, $now)) {829
$empty['shoot'] = [];830
$empty['ceasefire'] = true;831
} else {832
$empty['ceasefire'] = false;833
}834
return $empty;835
}836
837
/**838
* Apply a player action. $action = {type, ...}.839
* Types: move, shoot, give, upgrade, surrender, vote.840
*/841
public static function applyAction(array $game, string $userId, array $action, int $now): array842
{843
$game = self::applyDue($game, $now);844
if ($game['status'] !== 'running') {845
throw new RuntimeException('game_finished');846
}847
$type = (string) ($action['type'] ?? '');848
$me = self::player($game, $userId);849
if (!$me) {850
throw new RuntimeException('not_in_game');851
}852
853
if ($type === 'vote') {854
return self::actVote($game, $userId, $action, $now);855
}856
if ($type === 'surrender') {857
return self::actSurrender($game, $userId, $now);858
}859
if (empty($me['alive'])) {860
throw new RuntimeException('dead');861
}862
$legal = self::legal($game, $userId, $now);863
return match ($type) {864
'move' => self::actMove($game, $userId, $action, $legal, $now),865
'shoot' => self::actShoot($game, $userId, $action, $legal, $now),866
'give' => self::actGive($game, $userId, $action, $legal, $now),867
'upgrade' => self::actUpgrade($game, $userId, $legal, $now),868
default => throw new RuntimeException('unknown_action'),869
};870
}871
872
private static function spendAp(array &$game, string $userId, int $n = 1): void873
{874
$i = self::playerIndex($game, $userId);875
if ($i === null || (int) $game['players'][$i]['ap'] < $n) {876
throw new RuntimeException('no_ap');877
}878
$game['players'][$i]['ap'] = (int) $game['players'][$i]['ap'] - $n;879
}880
881
private static function actMove(array $game, string $userId, array $action, array $legal, int $now): array882
{883
$x = (int) ($action['x'] ?? -1);884
$y = (int) ($action['y'] ?? -1);885
$ok = false;886
foreach ($legal['move'] as $t) {887
if ((int) $t['x'] === $x && (int) $t['y'] === $y) {888
$ok = true;889
break;890
}891
}892
if (!$ok) {893
throw new RuntimeException('invalid_move');894
}895
self::spendAp($game, $userId, 1);896
$i = self::playerIndex($game, $userId);897
$from = ['x' => (int) $game['players'][$i]['x'], 'y' => (int) $game['players'][$i]['y']];898
$game['players'][$i]['x'] = $x;899
$game['players'][$i]['y'] = $y;900
self::pushEvent($game, 'move', [901
'player' => $userId,902
'from' => $from,903
'to' => ['x' => $x, 'y' => $y],904
'spend' => true,905
], $now);906
return $game;907
}908
909
private static function actShoot(array $game, string $userId, array $action, array $legal, int $now): array910
{911
if (self::ceasefireActive($game, $now)) {912
throw new RuntimeException('ceasefire');913
}914
$targetId = (string) ($action['target'] ?? '');915
if (!in_array($targetId, $legal['shoot'], true)) {916
throw new RuntimeException('out_of_range');917
}918
self::spendAp($game, $userId, 1);919
$ti = self::playerIndex($game, $targetId);920
$game['players'][$ti]['lives'] = (int) $game['players'][$ti]['lives'] - 1;921
$livesLeft = (int) $game['players'][$ti]['lives'];922
$killed = false;923
$loot = 0;924
if ($livesLeft <= 0) {925
$game['players'][$ti]['lives'] = 0;926
$game['players'][$ti]['alive'] = false;927
$killed = true;928
// AP loot (lobby option, default off): shooter takes the target's929
// remaining AP on an eliminating shot only. Shrink/surrender do not loot.930
if (!empty($game['rules']['ap_loot'])) {931
$loot = max(0, (int) $game['players'][$ti]['ap']);932
if ($loot > 0) {933
$si = self::playerIndex($game, $userId);934
if ($si !== null) {935
$game['players'][$si]['ap'] = (int) $game['players'][$si]['ap'] + $loot;936
}937
}938
}939
$game['players'][$ti]['ap'] = 0;940
}941
$shootEv = [942
'player' => $userId,943
'target' => $targetId,944
'lives_left' => max(0, $livesLeft),945
'damage' => 1,946
'killed' => $killed,947
'spend' => true,948
];949
if ($loot > 0) {950
$shootEv['loot'] = $loot;951
}952
self::pushEvent($game, 'shoot', $shootEv, $now);953
if ($killed) {954
$death = [955
'player' => $targetId,956
'cause' => 'shot',957
'by' => $userId,958
'spend' => false,959
];960
if ($loot > 0) {961
$death['loot'] = $loot;962
}963
self::pushEvent($game, 'death', $death, $now);964
$game = self::checkEnd($game, $now);965
}966
return $game;967
}968
969
private static function actGive(array $game, string $userId, array $action, array $legal, int $now): array970
{971
$targetId = (string) ($action['target'] ?? '');972
$amount = (int) ($action['amount'] ?? 0);973
if (!in_array($targetId, $legal['give'], true)) {974
throw new RuntimeException('out_of_range');975
}976
$me = self::player($game, $userId);977
if ($amount < 1 || $amount > (int) $me['ap']) {978
throw new RuntimeException('bad_give');979
}980
self::spendAp($game, $userId, $amount);981
$ti = self::playerIndex($game, $targetId);982
$game['players'][$ti]['ap'] = (int) $game['players'][$ti]['ap'] + $amount;983
self::pushEvent($game, 'give', [984
'player' => $userId,985
'target' => $targetId,986
'amount' => $amount,987
'spend' => true,988
], $now);989
return $game;990
}991
992
private static function actUpgrade(array $game, string $userId, array $legal, int $now): array993
{994
if (empty($legal['upgrade'])) {995
throw new RuntimeException('invalid_move');996
}997
self::spendAp($game, $userId, 1);998
$i = self::playerIndex($game, $userId);999
$game['players'][$i]['range'] = (int) $game['players'][$i]['range'] + 1;1000
self::pushEvent($game, 'upgrade', [1001
'player' => $userId,1002
'range' => (int) $game['players'][$i]['range'],1003
'spend' => true,1004
], $now);1005
return $game;1006
}1007
1008
private static function actSurrender(array $game, string $userId, int $now): array1009
{1010
$i = self::playerIndex($game, $userId);1011
if (empty($game['players'][$i]['alive'])) {1012
throw new RuntimeException('dead');1013
}1014
$game['players'][$i]['alive'] = false;1015
$game['players'][$i]['lives'] = 0;1016
$game['players'][$i]['ap'] = 0;1017
$game['players'][$i]['surrendered'] = true;1018
self::pushEvent($game, 'surrender', [1019
'player' => $userId,1020
'spend' => false,1021
], $now);1022
self::pushEvent($game, 'death', [1023
'player' => $userId,1024
'cause' => 'surrender',1025
'spend' => false,1026
], $now);1027
return self::checkEnd($game, $now);1028
}1029
1030
private static function actVote(array $game, string $userId, array $action, int $now): array1031
{1032
if (empty($game['rules']['jury'])) {1033
throw new RuntimeException('cannot_vote');1034
}1035
$me = self::player($game, $userId);1036
if (!$me || !empty($me['alive'])) {1037
throw new RuntimeException('cannot_vote');1038
}1039
$targetId = (string) ($action['target'] ?? '');1040
$t = self::player($game, $targetId);1041
if (!$t || empty($t['alive'])) {1042
throw new RuntimeException('bad_vote');1043
}1044
$game['votes'][$userId] = $targetId;1045
// Votes are secret: no public event, but version bumps so polls refresh.1046
$game['_vote_updated'] = $now;1047
$game['version'] = (int) ($game['version'] ?? 0) + 1;1048
return $game;1049
}1050
1051
public static function setNote(array $game, string $viewerId, string $subjectId, string $text): array1052
{1053
if (self::playerIndex($game, $viewerId) === null) {1054
throw new RuntimeException('not_in_game');1055
}1056
if (self::playerIndex($game, $subjectId) === null) {1057
throw new RuntimeException('not_in_game');1058
}1059
$text = trim($text);1060
if (mb_strlen($text) > self::NOTE_MAX) {1061
$text = mb_substr($text, 0, self::NOTE_MAX);1062
}1063
$key = $viewerId . "\0" . $subjectId;1064
if ($text === '') {1065
unset($game['notes'][$key]);1066
} else {1067
$game['notes'][$key] = $text;1068
}1069
$game['version'] = (int) ($game['version'] ?? 0) + 1;1070
return $game;1071
}1072
1073
public static function addMessage(array $game, string $fromId, string $toId, string $text, int $now): array1074
{1075
if (self::playerIndex($game, $fromId) === null || self::playerIndex($game, $toId) === null) {1076
throw new RuntimeException('not_in_game');1077
}1078
if ($fromId === $toId) {1079
throw new RuntimeException('invalid_move');1080
}1081
$text = trim($text);1082
if ($text === '' || mb_strlen($text) > self::CHAT_MAX) {1083
throw new RuntimeException('bad_give');1084
}1085
if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $text)) {1086
throw new RuntimeException('bad_give');1087
}1088
$game['messages'][] = [1089
'id' => count($game['messages']) + 1,1090
'from' => $fromId,1091
'to' => $toId,1092
'text' => $text,1093
't' => $now,1094
];1095
$game['version'] = (int) ($game['version'] ?? 0) + 1;1096
return $game;1097
}1098
1099
/**1100
* Viewer-specific presentation: hide others' votes and notes, hide1101
* other people's private chats, include legal actions and shrink ETA.1102
*/1103
1104
public static function visChoice(mixed $raw, array $allowed, string $default): string1105
{1106
if (is_string($raw) && in_array($raw, $allowed, true)) {1107
return $raw;1108
}1109
return $default;1110
}1111
1112
/**1113
* Per-viewer player card. Own lives/AP/range are always present.1114
* Movement, identity, and alive/dead are always public.1115
* Hidden numeric stats are omitted (null) so the API does not leak them.1116
*1117
* @param array<string,mixed> $game1118
* @param array<string,mixed> $p1119
* @return array<string,mixed>1120
*/1121
public static function presentPlayer(array $game, array $p, string $viewerId, string $noteKey): array1122
{1123
$rules = $game['rules'] ?? self::defaultRules();1124
$isSelf = $p['id'] === $viewerId;1125
$out = [1126
'id' => $p['id'],1127
'name' => $p['name'],1128
'avatar' => $p['avatar'],1129
'color' => $p['color'],1130
'x' => (int) $p['x'],1131
'y' => (int) $p['y'],1132
'alive' => !empty($p['alive']),1133
'surrendered' => !empty($p['surrendered']),1134
'is_you' => $isSelf,1135
'is_host' => $p['id'] === $game['host_id'],1136
'note' => $game['notes'][$noteKey] ?? '',1137
'lives' => null,1138
'ap' => null,1139
'range' => null,1140
];1141
if ($isSelf || ($rules['vis_lives'] ?? 'public') === 'public') {1142
$out['lives'] = (int) $p['lives'];1143
}1144
if ($isSelf || ($rules['vis_ap'] ?? 'public') === 'public') {1145
$out['ap'] = (int) $p['ap'];1146
}1147
if ($isSelf || ($rules['vis_range'] ?? 'public') === 'public') {1148
$out['range'] = (int) $p['range'];1149
} elseif (($rules['vis_range'] ?? 'public') === 'known_in_range'1150
&& self::viewerInRangeOf($game, $viewerId, $p)) {1151
$out['range'] = (int) $p['range'];1152
}1153
return $out;1154
}1155
1156
/**1157
* True when the viewer is within $subject's current firing range1158
* (Chebyshev, including diagonals). Used for vis_range = known_in_range.1159
*1160
* @param array<string,mixed> $game1161
* @param array<string,mixed> $subject1162
*/1163
public static function viewerInRangeOf(array $game, string $viewerId, array $subject): bool1164
{1165
$v = self::player($game, $viewerId);1166
if ($v === null) {1167
return false;1168
}1169
$dist = self::chebyshev((int) $v['x'], (int) $v['y'], (int) $subject['x'], (int) $subject['y']);1170
return $dist <= (int) $subject['range'];1171
}1172
1173
/**1174
* Whether $viewerId may see a shot event (who shot whom).1175
* The shooter always sees their own shot.1176
*/1177
public static function canSeeShot(array $rules, string $viewerId, string $shooter, string $target, bool $killed): bool1178
{1179
if ($viewerId === $shooter) {1180
return true;1181
}1182
$mode = $rules['vis_shots'] ?? 'public';1183
return match ($mode) {1184
'public' => true,1185
'elim_public' => $killed || $viewerId === $target,1186
'known_target' => $viewerId === $target,1187
'elim_known_target' => $killed && $viewerId === $target,1188
default => true,1189
};1190
}1191
1192
/**1193
* Filter the stored event log for one viewer. Hidden events are omitted1194
* entirely (no generic marker — a tick would leak that something happened).1195
* Returns clones; the stored game is never mutated.1196
*1197
* @return list<array<string,mixed>>1198
*/1199
public static function filterEvents(array $game, string $viewerId): array1200
{1201
$out = [];1202
foreach ($game['events'] ?? [] as $ev) {1203
$f = self::filterEvent($game, $ev, $viewerId);1204
if ($f !== null) {1205
$out[] = $f;1206
}1207
}1208
return $out;1209
}1210
1211
/**1212
* @param array<string,mixed> $ev1213
* @return array<string,mixed>|null1214
*/1215
public static function filterEvent(array $game, array $ev, string $viewerId): ?array1216
{1217
$rules = $game['rules'] ?? self::defaultRules();1218
$type = $ev['type'] ?? '';1219
$copy = $ev; // shallow copy; nested arrays are replaced when stripped1220
1221
if ($type === 'shoot') {1222
$shooter = (string) ($ev['player'] ?? '');1223
$target = (string) ($ev['target'] ?? '');1224
$killed = !empty($ev['killed']);1225
if (!self::canSeeShot($rules, $viewerId, $shooter, $target, $killed)) {1226
return null;1227
}1228
// Remaining lives belong to the target: only they (or public lives) may see them.1229
$livesPublic = ($rules['vis_lives'] ?? 'public') === 'public' || $viewerId === $target;1230
if (!$livesPublic) {1231
unset($copy['lives_left']);1232
}1233
$copy['damage'] = (int) ($ev['damage'] ?? 1);1234
// Loot is an AP amount: only the shooter (and public AP) may see it.1235
if (isset($copy['loot']) && ($rules['vis_ap'] ?? 'public') !== 'public'1236
&& $viewerId !== $shooter) {1237
unset($copy['loot']);1238
}1239
return $copy;1240
}1241
1242
if ($type === 'give') {1243
$giver = (string) ($ev['player'] ?? '');1244
$recipient = (string) ($ev['target'] ?? '');1245
$mode = $rules['vis_gifts'] ?? 'public';1246
if ($viewerId === $giver || $mode === 'public') {1247
return $copy;1248
}1249
if ($mode === 'known_recipient' && $viewerId === $recipient) {1250
return $copy;1251
}1252
if ($mode === 'anonymous' && $viewerId === $recipient) {1253
unset($copy['player']);1254
$copy['anonymous'] = true;1255
return $copy;1256
}1257
return null;1258
}1259
1260
if ($type === 'upgrade') {1261
$who = (string) ($ev['player'] ?? '');1262
if ($viewerId === $who) {1263
return $copy;1264
}1265
$mode = $rules['vis_range'] ?? 'public';1266
if ($mode === 'public') {1267
return $copy;1268
}1269
if ($mode === 'hidden') {1270
return null;1271
}1272
// known_in_range: visible iff the viewer may currently see that player's range.1273
$subj = self::player($game, $who);1274
if ($subj && self::viewerInRangeOf($game, $viewerId, $subj)) {1275
return $copy;1276
}1277
return null;1278
}1279
1280
if ($type === 'death') {1281
// Death (alive=false) is always public. Strip "by" if the eliminating1282
// shot is not visible to this viewer, so the killer is not leaked.1283
$cause = $ev['cause'] ?? '';1284
if ($cause === 'shot' && isset($ev['by'])) {1285
$killer = (string) $ev['by'];1286
$victim = (string) ($ev['player'] ?? '');1287
if (!self::canSeeShot($rules, $viewerId, $killer, $victim, true)) {1288
unset($copy['by']);1289
}1290
if (isset($copy['loot']) && ($rules['vis_ap'] ?? 'public') !== 'public'1291
&& $viewerId !== $killer) {1292
unset($copy['loot']);1293
}1294
}1295
return $copy;1296
}1297
1298
if ($type === 'daily') {1299
$mode = $rules['vis_ap'] ?? 'public';1300
if ($mode === 'hidden') {1301
$grants = $ev['grants'] ?? [];1302
if (is_array($grants)) {1303
$copy['grants'] = array_key_exists($viewerId, $grants)1304
? [$viewerId => $grants[$viewerId]]1305
: [];1306
}1307
}1308
// Jury winners stay public (the announced result). Vote counts, if1309
// present, are not needed by the client; strip to keep votes secret.1310
if (isset($copy['jury']) && is_array($copy['jury'])) {1311
$jury = $copy['jury'];1312
unset($jury['counts']);1313
$copy['jury'] = $jury;1314
}1315
return $copy;1316
}1317
1318
if ($type === 'shrink') {1319
// Movement in the report is public. The explicit "hurt" list leaks1320
// a life loss when lives are hidden — keep only the viewer's own id.1321
if (($rules['vis_lives'] ?? 'public') !== 'public') {1322
$hurt = $ev['hurt'] ?? [];1323
$copy['hurt'] = array_values(array_filter(1324
is_array($hurt) ? $hurt : [],1325
fn ($id) => $id === $viewerId1326
));1327
}1328
return $copy;1329
}1330
1331
// move, start, surrender, win, draw, shrink deaths: always visible.1332
return $copy;1333
}1334
1335
public static function present(array $game, string $viewerId, ?int $now = null): array1336
{1337
$now = $now ?? self::now();1338
$legal = $game['status'] === 'running' ? self::legal($game, $viewerId, $now) : [1339
'move' => [], 'shoot' => [], 'give' => [], 'upgrade' => false,1340
'surrender' => false, 'vote' => null, 'my_vote' => null,1341
];1342
$players = [];1343
foreach ($game['players'] as $p) {1344
$noteKey = $viewerId . "\0" . $p['id'];1345
$players[] = self::presentPlayer($game, $p, $viewerId, $noteKey);1346
}1347
$messages = [];1348
foreach ($game['messages'] as $m) {1349
if ($m['from'] === $viewerId || $m['to'] === $viewerId) {1350
$messages[] = $m;1351
}1352
}1353
$events = self::filterEvents($game, $viewerId);1354
$shrinkIn = self::daysUntilShrink($game);1355
return [1356
'id' => $game['id'],1357
'code' => $game['code'],1358
'host_id' => $game['host_id'],1359
'status' => $game['status'],1360
'created_at' => $game['created_at'],1361
'started_at' => $game['started_at'],1362
'finished_at' => $game['finished_at'],1363
'rules' => $game['rules'],1364
'grid' => (int) $game['grid'],1365
'day' => (int) $game['day'],1366
'next_distribution_at' => $game['next_distribution_at'],1367
'arena_inset' => (int) $game['arena_inset'],1368
'max_inset' => self::maxInset((int) $game['grid']),1369
'shrink_in_days' => $shrinkIn,1370
'winner_id' => $game['winner_id'],1371
'draw' => !empty($game['draw']),1372
'players' => $players,1373
'events' => $events,1374
'messages' => $messages,1375
'legal' => $legal,1376
'you' => $viewerId,1377
'timezone' => self::TZ,1378
'version' => (int) ($game['version'] ?? $game['event_seq'] ?? 0),1379
'server_now' => $now,1380
'ceasefire' => self::ceasefireInfo($game, $now),1381
];1382
}1383
1384
public static function lobbyView(array $game, string $viewerId): array1385
{1386
$players = [];1387
foreach ($game['players'] as $p) {1388
$players[] = [1389
'id' => $p['id'],1390
'name' => $p['name'],1391
'avatar' => $p['avatar'],1392
'color' => $p['color'],1393
'is_you' => $p['id'] === $viewerId,1394
'is_host' => $p['id'] === $game['host_id'],1395
];1396
}1397
return [1398
'id' => $game['id'],1399
'code' => $game['code'],1400
'host_id' => $game['host_id'],1401
'status' => $game['status'],1402
'created_at' => $game['created_at'],1403
'rules' => $game['rules'],1404
'players' => $players,1405
'can_start' => $game['status'] === 'lobby'1406
&& $game['host_id'] === $viewerId1407
&& count($game['players']) >= self::MIN_PLAYERS,1408
'you' => $viewerId,1409
'timezone' => self::TZ,1410
];1411
}1412
1413
public static function asBool(mixed $v): bool1414
{1415
if (is_bool($v)) {1416
return $v;1417
}1418
if (is_int($v) || is_float($v)) {1419
return $v != 0;1420
}1421
if (!is_string($v)) {1422
return (bool) $v;1423
}1424
$s = strtolower(trim($v));1425
return !in_array($s, ['', '0', 'false', 'off', 'no', 'null'], true);1426
}1427
1428
/**1429
* Normalise "HH:MM"-"HH:MM" ranges. Invalid entries are dropped.1430
* A range may wrap midnight (start > end). Zero-length (start==end) is dropped.1431
*1432
* @param mixed $raw1433
* @return list<array{start:string,end:string}>1434
*/1435
public static function normalizeRanges(mixed $raw): array1436
{1437
if (!is_array($raw)) {1438
return [];1439
}1440
$out = [];1441
$seen = [];1442
foreach ($raw as $r) {1443
if (!is_array($r)) {1444
continue;1445
}1446
$start = self::parseHm($r['start'] ?? $r[0] ?? null);1447
$end = self::parseHm($r['end'] ?? $r[1] ?? null);1448
if ($start === null || $end === null || $start === $end) {1449
continue;1450
}1451
$key = $start . '-' . $end;1452
if (isset($seen[$key])) {1453
continue;1454
}1455
$seen[$key] = true;1456
$out[] = ['start' => $start, 'end' => $end];1457
}1458
usort($out, fn ($a, $b) => strcmp($a['start'], $b['start']));1459
return array_slice($out, 0, 12);1460
}1461
1462
/** @return string|null "HH:MM" */1463
public static function parseHm(mixed $v): ?string1464
{1465
if (is_int($v)) {1466
if ($v < 0 || $v > 23 * 60 + 59) {1467
return null;1468
}1469
return sprintf('%02d:%02d', intdiv($v, 60), $v % 60);1470
}1471
if (!is_string($v)) {1472
return null;1473
}1474
$v = trim($v);1475
if (!preg_match('/^(\d{1,2}):(\d{2})$/', $v, $m)) {1476
return null;1477
}1478
$h = (int) $m[1];1479
$min = (int) $m[2];1480
if ($h > 23 || $min > 59) {1481
return null;1482
}1483
return sprintf('%02d:%02d', $h, $min);1484
}1485
1486
public static function hmToMinutes(string $hm): int1487
{1488
[$h, $m] = array_map('intval', explode(':', $hm));1489
return $h * 60 + $m;1490
}1491
1492
/**1493
* Convert a local Europe/Amsterdam wall-clock on a calendar date to unix.1494
* Uses midnight + hours/minutes so DST spring-forward skips and1495
* fall-back uses PHP's first occurrence, then addition continues correctly.1496
*/1497
public static function amsterdamWallclock(string $ymd, string $hm): int1498
{1499
$tz = new DateTimeZone(self::TZ);1500
$dt = new DateTime($ymd . ' 00:00:00', $tz);1501
$mins = self::hmToMinutes($hm);1502
if ($mins > 0) {1503
$dt->modify('+' . $mins . ' minutes');1504
}1505
return $dt->getTimestamp();1506
}1507
1508
/**1509
* Merged cease-fire intervals as [start_ts, end_ts] covering yesterday1510
* through two days ahead, so midnight wraps and DST are exact.1511
*1512
* @return list<array{0:int,1:int}>1513
*/1514
public static function ceasefireIntervals(array $ranges, int $now): array1515
{1516
if ($ranges === []) {1517
return [];1518
}1519
$tz = new DateTimeZone(self::TZ);1520
$anchor = (new DateTime('@' . $now))->setTimezone($tz);1521
$intervals = [];1522
for ($d = -1; $d <= 3; $d++) {1523
$day = (clone $anchor)->modify(($d >= 0 ? '+' : '') . $d . ' day');1524
$ymd = $day->format('Y-m-d');1525
$next = (clone $day)->modify('+1 day')->format('Y-m-d');1526
foreach ($ranges as $r) {1527
$startM = self::hmToMinutes($r['start']);1528
$endM = self::hmToMinutes($r['end']);1529
$startTs = self::amsterdamWallclock($ymd, $r['start']);1530
if ($endM > $startM) {1531
$endTs = self::amsterdamWallclock($ymd, $r['end']);1532
} else {1533
// Wraps midnight: ends on the next calendar day.1534
$endTs = self::amsterdamWallclock($next, $r['end']);1535
}1536
if ($endTs > $startTs) {1537
$intervals[] = [$startTs, $endTs];1538
}1539
}1540
}1541
if ($intervals === []) {1542
return [];1543
}1544
usort($intervals, fn ($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);1545
$merged = [];1546
foreach ($intervals as $iv) {1547
if ($merged === [] || $iv[0] > $merged[count($merged) - 1][1]) {1548
$merged[] = $iv;1549
} else {1550
$merged[count($merged) - 1][1] = max($merged[count($merged) - 1][1], $iv[1]);1551
}1552
}1553
return $merged;1554
}1555
1556
public static function ceasefireActive(array $game, int $now): bool1557
{1558
$info = self::ceasefireInfo($game, $now);1559
return $info !== null && !empty($info['active']);1560
}1561
1562
/**1563
* @return array{enabled:bool,active:bool,until:?int,seconds:int}|null1564
* null when the rule is off or there are no ranges.1565
*/1566
public static function ceasefireInfo(array $game, int $now): ?array1567
{1568
$rules = $game['rules'] ?? [];1569
if (empty($rules['ceasefire'])) {1570
return null;1571
}1572
$ranges = self::normalizeRanges($rules['ceasefire_ranges'] ?? []);1573
if ($ranges === []) {1574
return null;1575
}1576
$intervals = self::ceasefireIntervals($ranges, $now);1577
$active = false;1578
$until = null;1579
foreach ($intervals as $iv) {1580
if ($now >= $iv[0] && $now < $iv[1]) {1581
$active = true;1582
$until = $iv[1];1583
break;1584
}1585
if ($iv[0] > $now && ($until === null || $iv[0] < $until)) {1586
$until = $iv[0];1587
}1588
}1589
$seconds = $until !== null ? max(0, $until - $now) : 0;1590
return [1591
'enabled' => true,1592
'active' => $active,1593
'until' => $until,1594
'seconds' => $seconds,1595
'ranges' => $ranges,1596
];1597
}1598
1599
public static function generateCode(): string1600
{1601
// Crockford-ish, no 0/O/I/1/L.1602
$alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';1603
$len = strlen($alphabet);1604
$code = '';1605
for ($i = 0; $i < self::CODE_LEN; $i++) {1606
$code .= $alphabet[random_int(0, $len - 1)];1607
}1608
return $code;1609
}1610
1611
public static function generateId(): string1612
{1613
return bin2hex(random_bytes(12));1614
}1615
}@@ -0,0 +1,45 @@
1
<?php
2
declare(strict_types=1);
3
4
final class I18n
5
{
6
/** @var array<string, array<string, string>>|null */
7
private static ?array $locales = null;
8
9
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
10
11
public static function locale(): string
12
{
13
$c = $_COOKIE['allianties-locale'] ?? '';
14
$c = is_string($c) ? strtolower($c) : '';
15
if ($c === 'zh-hans' || $c === 'zh-cn') {
16
$c = 'zh';
17
}
18
return in_array($c, self::LOCALES, true) ? $c : 'en';
19
}
20
21
public static function t(string $key, array $params = [], ?string $locale = null): string
22
{
23
$locale = $locale ?? self::locale();
24
if (self::$locales === null) {
25
$raw = @file_get_contents(__DIR__ . '/i18n.json');
26
$data = $raw ? json_decode($raw, true) : null;
27
self::$locales = is_array($data['locales'] ?? null) ? $data['locales'] : [];
28
}
29
$s = self::$locales[$locale][$key] ?? self::$locales['en'][$key] ?? $key;
30
foreach ($params as $k => $v) {
31
$s = str_replace('{' . $k . '}', (string) $v, $s);
32
}
33
return $s;
34
}
35
36
public static function htmlLang(?string $locale = null): string
37
{
38
$map = [
39
'en' => 'en', 'nl' => 'nl', 'de' => 'de', 'fr' => 'fr', 'ja' => 'ja',
40
'zh' => 'zh-Hans', 'ko' => 'ko', 'pl' => 'pl', 'ru' => 'ru', 'es' => 'es',
41
];
42
$locale = $locale ?? self::locale();
43
return $map[$locale] ?? 'en';
44
}
45
}
@@ -0,0 +1,45 @@1
<?php2
declare(strict_types=1);3
4
final class I18n5
{6
/** @var array<string, array<string, string>>|null */7
private static ?array $locales = null;8
9
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];10
11
public static function locale(): string12
{13
$c = $_COOKIE['allianties-locale'] ?? '';14
$c = is_string($c) ? strtolower($c) : '';15
if ($c === 'zh-hans' || $c === 'zh-cn') {16
$c = 'zh';17
}18
return in_array($c, self::LOCALES, true) ? $c : 'en';19
}20
21
public static function t(string $key, array $params = [], ?string $locale = null): string22
{23
$locale = $locale ?? self::locale();24
if (self::$locales === null) {25
$raw = @file_get_contents(__DIR__ . '/i18n.json');26
$data = $raw ? json_decode($raw, true) : null;27
self::$locales = is_array($data['locales'] ?? null) ? $data['locales'] : [];28
}29
$s = self::$locales[$locale][$key] ?? self::$locales['en'][$key] ?? $key;30
foreach ($params as $k => $v) {31
$s = str_replace('{' . $k . '}', (string) $v, $s);32
}33
return $s;34
}35
36
public static function htmlLang(?string $locale = null): string37
{38
$map = [39
'en' => 'en', 'nl' => 'nl', 'de' => 'de', 'fr' => 'fr', 'ja' => 'ja',40
'zh' => 'zh-Hans', 'ko' => 'ko', 'pl' => 'pl', 'ru' => 'ru', 'es' => 'es',41
];42
$locale = $locale ?? self::locale();43
return $map[$locale] ?? 'en';44
}45
}@@ -0,0 +1,506 @@
1
<?php
2
declare(strict_types=1);
3
4
require_once __DIR__ . '/Engine.php';
5
require_once __DIR__ . '/I18n.php';
6
7
final class Store
8
{
9
private PDO $pdo;
10
private int $txDepth = 0;
11
12
public function __construct(PDO $pdo)
13
{
14
$this->pdo = $pdo;
15
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
16
$this->migrate();
17
}
18
19
public static function open(?string $dir = null): self
20
{
21
$dir = $dir ?? dataDir();
22
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
23
throw new RuntimeException('De datamap moet schrijfbaar zijn.');
24
}
25
$path = $dir . '/allianties.sqlite';
26
$pdo = new PDO('sqlite:' . $path, null, null, [
27
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
28
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
29
]);
30
$pdo->exec('PRAGMA journal_mode = WAL');
31
$pdo->exec('PRAGMA foreign_keys = ON');
32
$pdo->exec('PRAGMA busy_timeout = 4000');
33
return new self($pdo);
34
}
35
36
private function migrate(): void
37
{
38
$this->pdo->exec(<<<'SQL'
39
CREATE TABLE IF NOT EXISTS games (
40
id TEXT PRIMARY KEY,
41
code TEXT UNIQUE NOT NULL,
42
host_id TEXT NOT NULL,
43
status TEXT NOT NULL,
44
payload TEXT NOT NULL,
45
updated INTEGER NOT NULL
46
);
47
CREATE INDEX IF NOT EXISTS games_status ON games (status);
48
CREATE TABLE IF NOT EXISTS members (
49
game_id TEXT NOT NULL,
50
user_id TEXT NOT NULL,
51
PRIMARY KEY (game_id, user_id)
52
);
53
CREATE INDEX IF NOT EXISTS members_user ON members (user_id);
54
CREATE TABLE IF NOT EXISTS profiles (
55
user_id TEXT PRIMARY KEY,
56
locale TEXT,
57
avatar TEXT,
58
name TEXT,
59
updated INTEGER NOT NULL
60
);
61
SQL);
62
}
63
64
/** @template T @param callable():T $fn @return T */
65
public function tx(callable $fn): mixed
66
{
67
if ($this->txDepth === 0) {
68
$this->pdo->exec('BEGIN IMMEDIATE');
69
}
70
$this->txDepth++;
71
try {
72
$result = $fn();
73
$this->txDepth--;
74
if ($this->txDepth === 0) {
75
$this->pdo->exec('COMMIT');
76
}
77
return $result;
78
} catch (Throwable $e) {
79
if ($this->txDepth > 0) {
80
$this->txDepth = 0;
81
try {
82
$this->pdo->exec('ROLLBACK');
83
} catch (Throwable $ignored) {
84
}
85
}
86
throw $e;
87
}
88
}
89
90
public function now(): int
91
{
92
return Engine::now();
93
}
94
95
private function save(array $game): void
96
{
97
$now = $this->now();
98
$stmt = $this->pdo->prepare(
99
'INSERT INTO games (id, code, host_id, status, payload, updated)
100
VALUES (:id, :code, :host, :status, :payload, :updated)
101
ON CONFLICT(id) DO UPDATE SET
102
code = excluded.code,
103
host_id = excluded.host_id,
104
status = excluded.status,
105
payload = excluded.payload,
106
updated = excluded.updated'
107
);
108
$stmt->execute([
109
':id' => $game['id'],
110
':code' => $game['code'],
111
':host' => $game['host_id'],
112
':status' => $game['status'],
113
':payload' => json_encode($game, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
114
':updated' => $now,
115
]);
116
$this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$game['id']]);
117
$ins = $this->pdo->prepare('INSERT INTO members (game_id, user_id) VALUES (?, ?)');
118
foreach ($game['players'] as $p) {
119
$ins->execute([$game['id'], $p['id']]);
120
}
121
}
122
123
private function deleteGame(string $id): void
124
{
125
$this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$id]);
126
$this->pdo->prepare('DELETE FROM games WHERE id = ?')->execute([$id]);
127
}
128
129
public function load(string $id): ?array
130
{
131
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');
132
$stmt->execute([$id]);
133
$row = $stmt->fetch();
134
if (!$row) {
135
return null;
136
}
137
$game = json_decode((string) $row['payload'], true);
138
return is_array($game) ? $game : null;
139
}
140
141
public function loadByCode(string $code): ?array
142
{
143
$code = self::normalizeCode($code);
144
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE code = ?');
145
$stmt->execute([$code]);
146
$row = $stmt->fetch();
147
if (!$row) {
148
return null;
149
}
150
$game = json_decode((string) $row['payload'], true);
151
return is_array($game) ? $game : null;
152
}
153
154
public static function normalizeCode(string $code): string
155
{
156
$code = strtoupper(trim($code));
157
// Generated codes use Crockford-ish chars (no 0/O/I/1/L). Map lookalikes.
158
$code = strtr($code, ['O' => '0', 'I' => '1', 'L' => '1']);
159
$code = preg_replace('/[^A-Z0-9]/', '', $code) ?? '';
160
return $code;
161
}
162
163
/**
164
* Load, apply due events, run $fn, save. $fn receives and returns the game
165
* (or null to delete). Locked with BEGIN IMMEDIATE.
166
*
167
* @param callable(array):(?array) $fn
168
*/
169
public function mutate(string $id, callable $fn): ?array
170
{
171
return $this->tx(function () use ($id, $fn) {
172
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');
173
$stmt->execute([$id]);
174
$row = $stmt->fetch();
175
if (!$row) {
176
throw new RuntimeException('unknown_code');
177
}
178
$game = json_decode((string) $row['payload'], true);
179
if (!is_array($game)) {
180
throw new RuntimeException('unknown_code');
181
}
182
$game = Engine::applyDue($game, $this->now());
183
$game = $fn($game);
184
if ($game === null) {
185
$this->deleteGame($id);
186
return null;
187
}
188
$this->save($game);
189
return $game;
190
});
191
}
192
193
public function createLobby(string $userId, string $name, ?string $avatar, array $rules = []): array
194
{
195
return $this->tx(function () use ($userId, $name, $avatar, $rules) {
196
$now = $this->now();
197
$id = Engine::generateId();
198
$code = $this->uniqueCode();
199
$game = Engine::newLobby($id, $code, $userId, $name, $avatar, $rules, $now);
200
$this->save($game);
201
$this->touchProfile($userId, $name, $avatar);
202
return $game;
203
});
204
}
205
206
private function uniqueCode(): string
207
{
208
for ($i = 0; $i < 16; $i++) {
209
$code = Engine::generateCode();
210
$stmt = $this->pdo->prepare('SELECT 1 FROM games WHERE code = ?');
211
$stmt->execute([$code]);
212
if (!$stmt->fetch()) {
213
return $code;
214
}
215
}
216
throw new RuntimeException('generic');
217
}
218
219
public function joinByCode(string $userId, string $name, ?string $avatar, string $code): array
220
{
221
$code = self::normalizeCode($code);
222
if (strlen($code) < 4) {
223
throw new RuntimeException('unknown_code');
224
}
225
return $this->tx(function () use ($userId, $name, $avatar, $code) {
226
$stmt = $this->pdo->prepare('SELECT id, payload FROM games WHERE code = ?');
227
$stmt->execute([$code]);
228
$row = $stmt->fetch();
229
if (!$row) {
230
throw new RuntimeException('unknown_code');
231
}
232
$game = json_decode((string) $row['payload'], true);
233
if (!is_array($game)) {
234
throw new RuntimeException('unknown_code');
235
}
236
$game = Engine::applyDue($game, $this->now());
237
if ($game['status'] === 'lobby') {
238
$game = Engine::join($game, $userId, $name, $avatar, $this->now());
239
$this->save($game);
240
} elseif (Engine::playerIndex($game, $userId) === null) {
241
throw new RuntimeException('game_started');
242
} else {
243
$this->save($game); // persist any due distributions
244
}
245
$this->touchProfile($userId, $name, $avatar);
246
return $game;
247
});
248
}
249
250
public function leaveLobby(string $userId, string $gameId): ?array
251
{
252
return $this->mutate($gameId, function (array $game) use ($userId) {
253
return Engine::leaveLobby($game, $userId, $this->now());
254
});
255
}
256
257
public function setRules(string $userId, string $gameId, array $rules): array
258
{
259
$game = $this->mutate($gameId, function (array $game) use ($userId, $rules) {
260
return Engine::setLobbyRules($game, $userId, $rules);
261
});
262
if ($game === null) {
263
throw new RuntimeException('unknown_code');
264
}
265
return $game;
266
}
267
268
public function startGame(string $userId, string $gameId): array
269
{
270
$game = $this->mutate($gameId, function (array $game) use ($userId) {
271
return Engine::start($game, $userId, $this->now());
272
});
273
if ($game === null) {
274
throw new RuntimeException('unknown_code');
275
}
276
return $game;
277
}
278
279
public function act(string $userId, string $gameId, array $action): array
280
{
281
$game = $this->mutate($gameId, function (array $game) use ($userId, $action) {
282
return Engine::applyAction($game, $userId, $action, $this->now());
283
});
284
if ($game === null) {
285
throw new RuntimeException('unknown_code');
286
}
287
return $game;
288
}
289
290
public function setNote(string $userId, string $gameId, string $subjectId, string $text): array
291
{
292
$game = $this->mutate($gameId, function (array $game) use ($userId, $subjectId, $text) {
293
return Engine::setNote($game, $userId, $subjectId, $text);
294
});
295
if ($game === null) {
296
throw new RuntimeException('unknown_code');
297
}
298
return $game;
299
}
300
301
public function addMessage(string $userId, string $gameId, string $toId, string $text): array
302
{
303
$game = $this->mutate($gameId, function (array $game) use ($userId, $toId, $text) {
304
return Engine::addMessage($game, $userId, $toId, $text, $this->now());
305
});
306
if ($game === null) {
307
throw new RuntimeException('unknown_code');
308
}
309
return $game;
310
}
311
312
/**
313
* Local-dev helper: set next_distribution_at to $at (or now) so applyDue
314
* runs on the next mutate/present.
315
*/
316
public function debugAdvance(string $userId, string $gameId, ?int $at = null, int $days = 1): array
317
{
318
if (!localDev()) {
319
throw new RuntimeException('generic');
320
}
321
$at = $at ?? $this->now();
322
$game = $this->mutate($gameId, function (array $game) use ($userId, $at, $days) {
323
if (Engine::playerIndex($game, $userId) === null) {
324
throw new RuntimeException('not_in_game');
325
}
326
if ($game['status'] !== 'running') {
327
throw new RuntimeException('game_finished');
328
}
329
// Walk `$days` midnights into the past relative to "now" by
330
// setting next_distribution_at to a due timestamp, then applyDue
331
// already ran at the start of mutate — so we set it and apply again.
332
$target = $at;
333
$game['next_distribution_at'] = $target;
334
for ($i = 0; $i < max(1, $days); $i++) {
335
$game = Engine::applyDue($game, (int) $game['next_distribution_at']);
336
// applyDue moves next to the following midnight; to apply more,
337
// pull it back to "due" by using that new next as the time.
338
if ($i < $days - 1 && $game['status'] === 'running') {
339
$game = Engine::applyDue($game, (int) $game['next_distribution_at']);
340
}
341
}
342
return $game;
343
});
344
if ($game === null) {
345
throw new RuntimeException('unknown_code');
346
}
347
return $game;
348
}
349
350
public function present(string $userId, string $gameId): array
351
{
352
$game = $this->mutate($gameId, function (array $game) use ($userId) {
353
if (Engine::playerIndex($game, $userId) === null) {
354
throw new RuntimeException('not_in_game');
355
}
356
return $game;
357
});
358
if ($game === null) {
359
throw new RuntimeException('unknown_code');
360
}
361
return $this->view($game, $userId);
362
}
363
364
public function view(array $game, string $userId): array
365
{
366
if ($game['status'] === 'lobby') {
367
return Engine::lobbyView($game, $userId);
368
}
369
return Engine::present($game, $userId, $this->now());
370
}
371
372
public function sync(string $userId, string $gameId, int $since): array
373
{
374
return $this->tx(function () use ($userId, $gameId, $since) {
375
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');
376
$stmt->execute([$gameId]);
377
$row = $stmt->fetch();
378
if (!$row) {
379
throw new RuntimeException('unknown_code');
380
}
381
$game = json_decode((string) $row['payload'], true);
382
if (!is_array($game) || Engine::playerIndex($game, $userId) === null) {
383
throw new RuntimeException('not_in_game');
384
}
385
$before = (int) ($game['version'] ?? 0);
386
$due = Engine::applyDue($game, $this->now());
387
if ($due !== $game || (int) ($due['version'] ?? 0) !== $before) {
388
$this->save($due);
389
$game = $due;
390
} else {
391
$game = $due;
392
}
393
$version = (int) ($game['version'] ?? 0);
394
$now = $this->now();
395
$light = [
396
'ok' => true,
397
'changed' => $version !== $since,
398
'version' => $version,
399
'server_now' => $now,
400
'status' => $game['status'],
401
'next_distribution_at' => $game['next_distribution_at'] ?? null,
402
'ceasefire' => Engine::ceasefireInfo($game, $now),
403
'day' => (int) ($game['day'] ?? 0),
404
];
405
if ($version !== $since) {
406
$light['game'] = $this->view($game, $userId);
407
}
408
return $light;
409
});
410
}
411
412
/** @return list<array> */
413
public function listFor(string $userId): array
414
{
415
$stmt = $this->pdo->prepare(
416
'SELECT g.payload FROM members m JOIN games g ON g.id = m.game_id
417
WHERE m.user_id = ? ORDER BY g.updated DESC'
418
);
419
$stmt->execute([$userId]);
420
$out = [];
421
$now = $this->now();
422
foreach ($stmt->fetchAll() as $row) {
423
$game = json_decode((string) $row['payload'], true);
424
if (!is_array($game)) {
425
continue;
426
}
427
// Don't mutate here (listing is read-mostly); applyDue is cheap and
428
// in-memory only so the menu stays accurate if a day rolled over.
429
$game = Engine::applyDue($game, $now);
430
$me = Engine::player($game, $userId);
431
$alive = count(Engine::living($game));
432
$out[] = [
433
'id' => $game['id'],
434
'code' => $game['code'],
435
'status' => $game['status'],
436
'host_id' => $game['host_id'],
437
'is_host' => $game['host_id'] === $userId,
438
'players' => count($game['players']),
439
'alive' => $alive,
440
'day' => (int) ($game['day'] ?? 0),
441
'winner_id' => $game['winner_id'] ?? null,
442
'draw' => !empty($game['draw']),
443
'you_alive' => $me ? !empty($me['alive']) : false,
444
'you_won' => ($game['winner_id'] ?? null) === $userId,
445
'names' => array_map(fn ($p) => [
446
'id' => $p['id'],
447
'name' => $p['name'],
448
'color' => $p['color'] ?? null,
449
'avatar' => $p['avatar'] ?? null,
450
], $game['players']),
451
'updated_at' => $game['started_at'] ?? $game['created_at'] ?? 0,
452
'rules' => $game['rules'] ?? Engine::defaultRules(),
453
];
454
}
455
return $out;
456
}
457
458
public function ensureProfile(string $userId): array
459
{
460
$stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
461
$stmt->execute([$userId]);
462
$row = $stmt->fetch();
463
if ($row) {
464
return $row;
465
}
466
$this->pdo->prepare(
467
'INSERT INTO profiles (user_id, locale, avatar, name, updated) VALUES (?, NULL, NULL, NULL, ?)'
468
)->execute([$userId, $this->now()]);
469
return [
470
'user_id' => $userId,
471
'locale' => null,
472
'avatar' => null,
473
'name' => null,
474
'updated' => $this->now(),
475
];
476
}
477
478
public function touchProfile(string $userId, string $name, ?string $avatar): void
479
{
480
$this->ensureProfile($userId);
481
$this->pdo->prepare(
482
'UPDATE profiles SET name = ?, avatar = COALESCE(?, avatar), updated = ? WHERE user_id = ?'
483
)->execute([$name, $avatar, $this->now(), $userId]);
484
}
485
486
public function locale(string $userId): ?string
487
{
488
$v = $this->ensureProfile($userId)['locale'] ?? null;
489
return is_string($v) && $v !== '' ? $v : null;
490
}
491
492
public function setLocale(string $userId, string $locale): string
493
{
494
$locale = strtolower($locale);
495
if ($locale === 'zh-hans' || $locale === 'zh-cn') {
496
$locale = 'zh';
497
}
498
if (!in_array($locale, I18n::LOCALES, true)) {
499
throw new RuntimeException('generic');
500
}
501
$this->ensureProfile($userId);
502
$this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
503
->execute([$locale, $this->now(), $userId]);
504
return $locale;
505
}
506
}
@@ -0,0 +1,506 @@1
<?php2
declare(strict_types=1);3
4
require_once __DIR__ . '/Engine.php';5
require_once __DIR__ . '/I18n.php';6
7
final class Store8
{9
private PDO $pdo;10
private int $txDepth = 0;11
12
public function __construct(PDO $pdo)13
{14
$this->pdo = $pdo;15
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);16
$this->migrate();17
}18
19
public static function open(?string $dir = null): self20
{21
$dir = $dir ?? dataDir();22
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {23
throw new RuntimeException('De datamap moet schrijfbaar zijn.');24
}25
$path = $dir . '/allianties.sqlite';26
$pdo = new PDO('sqlite:' . $path, null, null, [27
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,28
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,29
]);30
$pdo->exec('PRAGMA journal_mode = WAL');31
$pdo->exec('PRAGMA foreign_keys = ON');32
$pdo->exec('PRAGMA busy_timeout = 4000');33
return new self($pdo);34
}35
36
private function migrate(): void37
{38
$this->pdo->exec(<<<'SQL'39
CREATE TABLE IF NOT EXISTS games (40
id TEXT PRIMARY KEY,41
code TEXT UNIQUE NOT NULL,42
host_id TEXT NOT NULL,43
status TEXT NOT NULL,44
payload TEXT NOT NULL,45
updated INTEGER NOT NULL46
);47
CREATE INDEX IF NOT EXISTS games_status ON games (status);48
CREATE TABLE IF NOT EXISTS members (49
game_id TEXT NOT NULL,50
user_id TEXT NOT NULL,51
PRIMARY KEY (game_id, user_id)52
);53
CREATE INDEX IF NOT EXISTS members_user ON members (user_id);54
CREATE TABLE IF NOT EXISTS profiles (55
user_id TEXT PRIMARY KEY,56
locale TEXT,57
avatar TEXT,58
name TEXT,59
updated INTEGER NOT NULL60
);61
SQL);62
}63
64
/** @template T @param callable():T $fn @return T */65
public function tx(callable $fn): mixed66
{67
if ($this->txDepth === 0) {68
$this->pdo->exec('BEGIN IMMEDIATE');69
}70
$this->txDepth++;71
try {72
$result = $fn();73
$this->txDepth--;74
if ($this->txDepth === 0) {75
$this->pdo->exec('COMMIT');76
}77
return $result;78
} catch (Throwable $e) {79
if ($this->txDepth > 0) {80
$this->txDepth = 0;81
try {82
$this->pdo->exec('ROLLBACK');83
} catch (Throwable $ignored) {84
}85
}86
throw $e;87
}88
}89
90
public function now(): int91
{92
return Engine::now();93
}94
95
private function save(array $game): void96
{97
$now = $this->now();98
$stmt = $this->pdo->prepare(99
'INSERT INTO games (id, code, host_id, status, payload, updated)100
VALUES (:id, :code, :host, :status, :payload, :updated)101
ON CONFLICT(id) DO UPDATE SET102
code = excluded.code,103
host_id = excluded.host_id,104
status = excluded.status,105
payload = excluded.payload,106
updated = excluded.updated'107
);108
$stmt->execute([109
':id' => $game['id'],110
':code' => $game['code'],111
':host' => $game['host_id'],112
':status' => $game['status'],113
':payload' => json_encode($game, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),114
':updated' => $now,115
]);116
$this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$game['id']]);117
$ins = $this->pdo->prepare('INSERT INTO members (game_id, user_id) VALUES (?, ?)');118
foreach ($game['players'] as $p) {119
$ins->execute([$game['id'], $p['id']]);120
}121
}122
123
private function deleteGame(string $id): void124
{125
$this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$id]);126
$this->pdo->prepare('DELETE FROM games WHERE id = ?')->execute([$id]);127
}128
129
public function load(string $id): ?array130
{131
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');132
$stmt->execute([$id]);133
$row = $stmt->fetch();134
if (!$row) {135
return null;136
}137
$game = json_decode((string) $row['payload'], true);138
return is_array($game) ? $game : null;139
}140
141
public function loadByCode(string $code): ?array142
{143
$code = self::normalizeCode($code);144
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE code = ?');145
$stmt->execute([$code]);146
$row = $stmt->fetch();147
if (!$row) {148
return null;149
}150
$game = json_decode((string) $row['payload'], true);151
return is_array($game) ? $game : null;152
}153
154
public static function normalizeCode(string $code): string155
{156
$code = strtoupper(trim($code));157
// Generated codes use Crockford-ish chars (no 0/O/I/1/L). Map lookalikes.158
$code = strtr($code, ['O' => '0', 'I' => '1', 'L' => '1']);159
$code = preg_replace('/[^A-Z0-9]/', '', $code) ?? '';160
return $code;161
}162
163
/**164
* Load, apply due events, run $fn, save. $fn receives and returns the game165
* (or null to delete). Locked with BEGIN IMMEDIATE.166
*167
* @param callable(array):(?array) $fn168
*/169
public function mutate(string $id, callable $fn): ?array170
{171
return $this->tx(function () use ($id, $fn) {172
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');173
$stmt->execute([$id]);174
$row = $stmt->fetch();175
if (!$row) {176
throw new RuntimeException('unknown_code');177
}178
$game = json_decode((string) $row['payload'], true);179
if (!is_array($game)) {180
throw new RuntimeException('unknown_code');181
}182
$game = Engine::applyDue($game, $this->now());183
$game = $fn($game);184
if ($game === null) {185
$this->deleteGame($id);186
return null;187
}188
$this->save($game);189
return $game;190
});191
}192
193
public function createLobby(string $userId, string $name, ?string $avatar, array $rules = []): array194
{195
return $this->tx(function () use ($userId, $name, $avatar, $rules) {196
$now = $this->now();197
$id = Engine::generateId();198
$code = $this->uniqueCode();199
$game = Engine::newLobby($id, $code, $userId, $name, $avatar, $rules, $now);200
$this->save($game);201
$this->touchProfile($userId, $name, $avatar);202
return $game;203
});204
}205
206
private function uniqueCode(): string207
{208
for ($i = 0; $i < 16; $i++) {209
$code = Engine::generateCode();210
$stmt = $this->pdo->prepare('SELECT 1 FROM games WHERE code = ?');211
$stmt->execute([$code]);212
if (!$stmt->fetch()) {213
return $code;214
}215
}216
throw new RuntimeException('generic');217
}218
219
public function joinByCode(string $userId, string $name, ?string $avatar, string $code): array220
{221
$code = self::normalizeCode($code);222
if (strlen($code) < 4) {223
throw new RuntimeException('unknown_code');224
}225
return $this->tx(function () use ($userId, $name, $avatar, $code) {226
$stmt = $this->pdo->prepare('SELECT id, payload FROM games WHERE code = ?');227
$stmt->execute([$code]);228
$row = $stmt->fetch();229
if (!$row) {230
throw new RuntimeException('unknown_code');231
}232
$game = json_decode((string) $row['payload'], true);233
if (!is_array($game)) {234
throw new RuntimeException('unknown_code');235
}236
$game = Engine::applyDue($game, $this->now());237
if ($game['status'] === 'lobby') {238
$game = Engine::join($game, $userId, $name, $avatar, $this->now());239
$this->save($game);240
} elseif (Engine::playerIndex($game, $userId) === null) {241
throw new RuntimeException('game_started');242
} else {243
$this->save($game); // persist any due distributions244
}245
$this->touchProfile($userId, $name, $avatar);246
return $game;247
});248
}249
250
public function leaveLobby(string $userId, string $gameId): ?array251
{252
return $this->mutate($gameId, function (array $game) use ($userId) {253
return Engine::leaveLobby($game, $userId, $this->now());254
});255
}256
257
public function setRules(string $userId, string $gameId, array $rules): array258
{259
$game = $this->mutate($gameId, function (array $game) use ($userId, $rules) {260
return Engine::setLobbyRules($game, $userId, $rules);261
});262
if ($game === null) {263
throw new RuntimeException('unknown_code');264
}265
return $game;266
}267
268
public function startGame(string $userId, string $gameId): array269
{270
$game = $this->mutate($gameId, function (array $game) use ($userId) {271
return Engine::start($game, $userId, $this->now());272
});273
if ($game === null) {274
throw new RuntimeException('unknown_code');275
}276
return $game;277
}278
279
public function act(string $userId, string $gameId, array $action): array280
{281
$game = $this->mutate($gameId, function (array $game) use ($userId, $action) {282
return Engine::applyAction($game, $userId, $action, $this->now());283
});284
if ($game === null) {285
throw new RuntimeException('unknown_code');286
}287
return $game;288
}289
290
public function setNote(string $userId, string $gameId, string $subjectId, string $text): array291
{292
$game = $this->mutate($gameId, function (array $game) use ($userId, $subjectId, $text) {293
return Engine::setNote($game, $userId, $subjectId, $text);294
});295
if ($game === null) {296
throw new RuntimeException('unknown_code');297
}298
return $game;299
}300
301
public function addMessage(string $userId, string $gameId, string $toId, string $text): array302
{303
$game = $this->mutate($gameId, function (array $game) use ($userId, $toId, $text) {304
return Engine::addMessage($game, $userId, $toId, $text, $this->now());305
});306
if ($game === null) {307
throw new RuntimeException('unknown_code');308
}309
return $game;310
}311
312
/**313
* Local-dev helper: set next_distribution_at to $at (or now) so applyDue314
* runs on the next mutate/present.315
*/316
public function debugAdvance(string $userId, string $gameId, ?int $at = null, int $days = 1): array317
{318
if (!localDev()) {319
throw new RuntimeException('generic');320
}321
$at = $at ?? $this->now();322
$game = $this->mutate($gameId, function (array $game) use ($userId, $at, $days) {323
if (Engine::playerIndex($game, $userId) === null) {324
throw new RuntimeException('not_in_game');325
}326
if ($game['status'] !== 'running') {327
throw new RuntimeException('game_finished');328
}329
// Walk `$days` midnights into the past relative to "now" by330
// setting next_distribution_at to a due timestamp, then applyDue331
// already ran at the start of mutate — so we set it and apply again.332
$target = $at;333
$game['next_distribution_at'] = $target;334
for ($i = 0; $i < max(1, $days); $i++) {335
$game = Engine::applyDue($game, (int) $game['next_distribution_at']);336
// applyDue moves next to the following midnight; to apply more,337
// pull it back to "due" by using that new next as the time.338
if ($i < $days - 1 && $game['status'] === 'running') {339
$game = Engine::applyDue($game, (int) $game['next_distribution_at']);340
}341
}342
return $game;343
});344
if ($game === null) {345
throw new RuntimeException('unknown_code');346
}347
return $game;348
}349
350
public function present(string $userId, string $gameId): array351
{352
$game = $this->mutate($gameId, function (array $game) use ($userId) {353
if (Engine::playerIndex($game, $userId) === null) {354
throw new RuntimeException('not_in_game');355
}356
return $game;357
});358
if ($game === null) {359
throw new RuntimeException('unknown_code');360
}361
return $this->view($game, $userId);362
}363
364
public function view(array $game, string $userId): array365
{366
if ($game['status'] === 'lobby') {367
return Engine::lobbyView($game, $userId);368
}369
return Engine::present($game, $userId, $this->now());370
}371
372
public function sync(string $userId, string $gameId, int $since): array373
{374
return $this->tx(function () use ($userId, $gameId, $since) {375
$stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?');376
$stmt->execute([$gameId]);377
$row = $stmt->fetch();378
if (!$row) {379
throw new RuntimeException('unknown_code');380
}381
$game = json_decode((string) $row['payload'], true);382
if (!is_array($game) || Engine::playerIndex($game, $userId) === null) {383
throw new RuntimeException('not_in_game');384
}385
$before = (int) ($game['version'] ?? 0);386
$due = Engine::applyDue($game, $this->now());387
if ($due !== $game || (int) ($due['version'] ?? 0) !== $before) {388
$this->save($due);389
$game = $due;390
} else {391
$game = $due;392
}393
$version = (int) ($game['version'] ?? 0);394
$now = $this->now();395
$light = [396
'ok' => true,397
'changed' => $version !== $since,398
'version' => $version,399
'server_now' => $now,400
'status' => $game['status'],401
'next_distribution_at' => $game['next_distribution_at'] ?? null,402
'ceasefire' => Engine::ceasefireInfo($game, $now),403
'day' => (int) ($game['day'] ?? 0),404
];405
if ($version !== $since) {406
$light['game'] = $this->view($game, $userId);407
}408
return $light;409
});410
}411
412
/** @return list<array> */413
public function listFor(string $userId): array414
{415
$stmt = $this->pdo->prepare(416
'SELECT g.payload FROM members m JOIN games g ON g.id = m.game_id417
WHERE m.user_id = ? ORDER BY g.updated DESC'418
);419
$stmt->execute([$userId]);420
$out = [];421
$now = $this->now();422
foreach ($stmt->fetchAll() as $row) {423
$game = json_decode((string) $row['payload'], true);424
if (!is_array($game)) {425
continue;426
}427
// Don't mutate here (listing is read-mostly); applyDue is cheap and428
// in-memory only so the menu stays accurate if a day rolled over.429
$game = Engine::applyDue($game, $now);430
$me = Engine::player($game, $userId);431
$alive = count(Engine::living($game));432
$out[] = [433
'id' => $game['id'],434
'code' => $game['code'],435
'status' => $game['status'],436
'host_id' => $game['host_id'],437
'is_host' => $game['host_id'] === $userId,438
'players' => count($game['players']),439
'alive' => $alive,440
'day' => (int) ($game['day'] ?? 0),441
'winner_id' => $game['winner_id'] ?? null,442
'draw' => !empty($game['draw']),443
'you_alive' => $me ? !empty($me['alive']) : false,444
'you_won' => ($game['winner_id'] ?? null) === $userId,445
'names' => array_map(fn ($p) => [446
'id' => $p['id'],447
'name' => $p['name'],448
'color' => $p['color'] ?? null,449
'avatar' => $p['avatar'] ?? null,450
], $game['players']),451
'updated_at' => $game['started_at'] ?? $game['created_at'] ?? 0,452
'rules' => $game['rules'] ?? Engine::defaultRules(),453
];454
}455
return $out;456
}457
458
public function ensureProfile(string $userId): array459
{460
$stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');461
$stmt->execute([$userId]);462
$row = $stmt->fetch();463
if ($row) {464
return $row;465
}466
$this->pdo->prepare(467
'INSERT INTO profiles (user_id, locale, avatar, name, updated) VALUES (?, NULL, NULL, NULL, ?)'468
)->execute([$userId, $this->now()]);469
return [470
'user_id' => $userId,471
'locale' => null,472
'avatar' => null,473
'name' => null,474
'updated' => $this->now(),475
];476
}477
478
public function touchProfile(string $userId, string $name, ?string $avatar): void479
{480
$this->ensureProfile($userId);481
$this->pdo->prepare(482
'UPDATE profiles SET name = ?, avatar = COALESCE(?, avatar), updated = ? WHERE user_id = ?'483
)->execute([$name, $avatar, $this->now(), $userId]);484
}485
486
public function locale(string $userId): ?string487
{488
$v = $this->ensureProfile($userId)['locale'] ?? null;489
return is_string($v) && $v !== '' ? $v : null;490
}491
492
public function setLocale(string $userId, string $locale): string493
{494
$locale = strtolower($locale);495
if ($locale === 'zh-hans' || $locale === 'zh-cn') {496
$locale = 'zh';497
}498
if (!in_array($locale, I18n::LOCALES, true)) {499
throw new RuntimeException('generic');500
}501
$this->ensureProfile($userId);502
$this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')503
->execute([$locale, $this->now(), $userId]);504
return $locale;505
}506
}@@ -0,0 +1,361 @@
1
<?php
2
declare(strict_types=1);
3
4
const ALLIANTIES_SESSION_TTL = 86400 * 30;
5
const ALLIANTIES_DEFAULT_AUTH = 'https://auth.timfalken.com';
6
const ALLIANTIES_DEFAULT_CLIENT_ID = 'projects.timfalken.com';
7
const ALLIANTIES_DEFAULT_BASE = 'https://projects.timfalken.com/allianties';
8
const ALLIANTIES_TEST_USERS = 8;
9
10
function dataDir(): string
11
{
12
$override = getenv('ALLIANTIES_DATA_DIR');
13
if (is_string($override) && $override !== '') {
14
return rtrim($override, '/');
15
}
16
return dirname(__DIR__) . '/data';
17
}
18
19
function ensureDataDir(): string
20
{
21
$dir = dataDir();
22
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
23
throw new RuntimeException('De datamap moet schrijfbaar zijn.');
24
}
25
$deny = $dir . '/.htaccess';
26
if (!is_file($deny)) {
27
@file_put_contents($deny, "Require all denied\n");
28
}
29
$sessions = $dir . '/sessions';
30
if (!is_dir($sessions)) {
31
@mkdir($sessions, 0775, true);
32
}
33
return $dir;
34
}
35
36
function localDev(): bool
37
{
38
$host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
39
return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
40
&& in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
41
}
42
43
function config(): array
44
{
45
$dir = ensureDataDir();
46
$path = $dir . '/config.php';
47
$lock = fopen($dir . '/config.lock', 'c');
48
if ($lock === false) {
49
throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
50
}
51
try {
52
if (!flock($lock, LOCK_EX)) {
53
throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
54
}
55
if (!is_file($path)) {
56
$template = <<<'PHP'
57
<?php
58
// Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.
59
// Productie-URL: https://projects.timfalken.com/allianties
60
// client_id is het geregistreerde domein: projects.timfalken.com.
61
// Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim
62
// van dit domein; NIET opnieuw genereren, dat breekt de andere sites).
63
// Voeg daar ook het callback-pad /allianties/callback.php toe.
64
// Dit bestand wordt niet gedeployed en staat niet in git.
65
return [
66
'auth_url' => 'https://auth.timfalken.com',
67
'base_url' => 'https://projects.timfalken.com/allianties',
68
'client_id' => 'projects.timfalken.com',
69
'client_secret' => '',
70
];
71
PHP;
72
if (file_put_contents($path, $template) !== strlen($template)) {
73
throw new RuntimeException('data/config.php kon niet worden gemaakt.');
74
}
75
}
76
$values = require $path;
77
if (!is_array($values)) {
78
throw new RuntimeException('data/config.php moet een array teruggeven.');
79
}
80
} finally {
81
flock($lock, LOCK_UN);
82
fclose($lock);
83
}
84
foreach ([
85
'auth_url' => 'ALLIANTIES_AUTH_URL',
86
'base_url' => 'ALLIANTIES_BASE_URL',
87
'client_id' => 'ALLIANTIES_CLIENT_ID',
88
'client_secret' => 'ALLIANTIES_CLIENT_SECRET',
89
] as $key => $env) {
90
if (($values[$key] ?? '') === '') {
91
$values[$key] = getenv($env) ?: '';
92
}
93
}
94
if (($values['auth_url'] ?? '') === '') {
95
$values['auth_url'] = ALLIANTIES_DEFAULT_AUTH;
96
}
97
if (($values['client_id'] ?? '') === '') {
98
$values['client_id'] = ALLIANTIES_DEFAULT_CLIENT_ID;
99
}
100
return $values;
101
}
102
103
function authConfigured(): bool
104
{
105
$c = config();
106
return ($c['client_secret'] ?? '') !== ''
107
&& ($c['client_id'] ?? '') !== ''
108
&& ($c['base_url'] ?? '') !== '';
109
}
110
111
function baseUrl(): string
112
{
113
if (localDev()) {
114
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
115
if ($dir === '/' || $dir === '.') {
116
$dir = '';
117
}
118
return 'http://' . $_SERVER['HTTP_HOST'] . $dir;
119
}
120
$base = rtrim((string) (config()['base_url'] ?? ''), '/');
121
if (!str_starts_with($base, 'https://')) {
122
throw new RuntimeException(
123
"Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "
124
. '(https://projects.timfalken.com/allianties), of zet ALLIANTIES_BASE_URL.'
125
);
126
}
127
return $base;
128
}
129
130
function authUrl(): string
131
{
132
$url = rtrim((string) (config()['auth_url'] ?? ALLIANTIES_DEFAULT_AUTH), '/');
133
return $url !== '' ? $url : ALLIANTIES_DEFAULT_AUTH;
134
}
135
136
function authRequest(string $path, ?array $form = null, ?string $token = null): array
137
{
138
$ch = curl_init(authUrl() . $path);
139
$headers = ['Accept: application/json', 'User-Agent: Allianties/1.0'];
140
if ($token) {
141
$headers[] = 'Authorization: Bearer ' . $token;
142
}
143
curl_setopt_array($ch, [
144
CURLOPT_RETURNTRANSFER => true,
145
CURLOPT_TIMEOUT => 15,
146
CURLOPT_HTTPHEADER => $headers,
147
]);
148
if ($form !== null) {
149
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
150
}
151
$body = curl_exec($ch);
152
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
153
$err = curl_error($ch);
154
curl_close($ch);
155
$data = is_string($body) ? json_decode($body, true) : null;
156
if ($status !== 200 || !is_array($data)) {
157
$hint = $err !== '' ? ' (' . $err . ')' : '';
158
throw new RuntimeException(
159
'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint
160
);
161
}
162
return $data;
163
}
164
165
/** @return array{0:string,1:string,2:?string} id, name, avatar */
166
function authIdentity(array $profile): array
167
{
168
if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
169
throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
170
}
171
$raw = $profile['id'];
172
$numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
173
if (!$numeric || (int) $raw < 1) {
174
throw new RuntimeException('Ongeldig account-id.');
175
}
176
$id = (int) $raw;
177
$avatar = null;
178
foreach (['avatar_url', 'avatar', 'picture', 'icon', 'image'] as $k) {
179
if (isset($profile[$k]) && is_string($profile[$k]) && str_starts_with($profile[$k], 'https://')) {
180
$avatar = $profile[$k];
181
break;
182
}
183
}
184
if ($avatar === null) {
185
$avatar = authUrl() . '/avatar/' . $id;
186
}
187
return ['auth:' . $id, $profile['username'], $avatar];
188
}
189
190
function isValidUserId(string $id): bool
191
{
192
if (preg_match('/^auth:[1-9][0-9]{0,17}$/', $id)) {
193
return true;
194
}
195
return (bool) preg_match('/^local:test_user_([1-9]|1[0-6])$/', $id);
196
}
197
198
function loginUser(string $id, string $name, ?string $avatar = null): void
199
{
200
if (!isValidUserId($id)) {
201
throw new RuntimeException('Ongeldig account.');
202
}
203
$name = trim($name);
204
if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
205
throw new RuntimeException('Ongeldige gebruikersnaam.');
206
}
207
session_regenerate_id(true);
208
$_SESSION['user'] = $id;
209
$_SESSION['name'] = $name;
210
$_SESSION['avatar'] = $avatar;
211
$_SESSION['csrf'] = bin2hex(random_bytes(24));
212
$_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL;
213
}
214
215
function logoutUser(): void
216
{
217
$_SESSION = [];
218
if (ini_get('session.use_cookies')) {
219
$p = session_get_cookie_params();
220
setcookie(session_name(), '', [
221
'expires' => time() - 3600,
222
'path' => $p['path'] ?? '/',
223
'secure' => (bool) ($p['secure'] ?? false),
224
'httponly' => true,
225
'samesite' => 'Lax',
226
]);
227
}
228
session_destroy();
229
}
230
231
function currentUser(): ?array
232
{
233
$id = $_SESSION['user'] ?? null;
234
$name = $_SESSION['name'] ?? null;
235
if (!is_string($id) || $id === '' || !is_string($name)) {
236
return null;
237
}
238
if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
239
return null;
240
}
241
$avatar = $_SESSION['avatar'] ?? null;
242
return [
243
'id' => $id,
244
'name' => $name,
245
'avatar' => is_string($avatar) ? $avatar : null,
246
];
247
}
248
249
function requireUser(): array
250
{
251
$u = currentUser();
252
if (!$u) {
253
jsonFail('login', 401);
254
}
255
return $u;
256
}
257
258
function csrfToken(): string
259
{
260
if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
261
$_SESSION['csrf'] = bin2hex(random_bytes(24));
262
}
263
return $_SESSION['csrf'];
264
}
265
266
function requireCsrf(): void
267
{
268
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
269
return;
270
}
271
$got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
272
if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
273
jsonFail('csrf', 403);
274
}
275
}
276
277
function jsonOut(array $data, int $status = 200): never
278
{
279
http_response_code($status);
280
header('Content-Type: application/json; charset=utf-8');
281
header('Cache-Control: no-store');
282
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
283
exit;
284
}
285
286
function jsonFail(string $message, int $status = 400): never
287
{
288
jsonOut(['ok' => false, 'error' => $message], $status);
289
}
290
291
function readJsonBody(): array
292
{
293
$raw = file_get_contents('php://input');
294
if (!is_string($raw) || $raw === '') {
295
return $_POST;
296
}
297
$data = json_decode($raw, true);
298
return is_array($data) ? $data : [];
299
}
300
301
function safeNext(mixed $next): ?string
302
{
303
if (!is_string($next) || $next === '') {
304
return null;
305
}
306
// Only a relative path on this app, no scheme, no protocol-relative, no backslash.
307
if (preg_match('#^[a-z]+://#i', $next) || str_starts_with($next, '//') || str_contains($next, '\\')) {
308
return null;
309
}
310
if ($next[0] === '/') {
311
return null;
312
}
313
if (!preg_match('@^[A-Za-z0-9._~/?\#=&%\-]+$@', $next)) {
314
return null;
315
}
316
return $next;
317
}
318
319
function startAlliantiesSession(): void
320
{
321
if (session_status() === PHP_SESSION_ACTIVE) {
322
return;
323
}
324
$dir = ensureDataDir() . '/sessions';
325
if (!is_dir($dir)) {
326
@mkdir($dir, 0775, true);
327
}
328
session_name('allianties_session');
329
ini_set('session.use_strict_mode', '1');
330
ini_set('session.gc_maxlifetime', (string) ALLIANTIES_SESSION_TTL);
331
session_save_path($dir);
332
$path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
333
if ($path === '//') {
334
$path = '/';
335
}
336
$secure = !localDev();
337
session_set_cookie_params([
338
'lifetime' => ALLIANTIES_SESSION_TTL,
339
'path' => $path,
340
'secure' => $secure,
341
'httponly' => true,
342
'samesite' => 'Lax',
343
]);
344
session_start();
345
if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
346
setcookie(session_name(), session_id(), [
347
'expires' => time() + ALLIANTIES_SESSION_TTL,
348
'path' => $path,
349
'secure' => $secure,
350
'httponly' => true,
351
'samesite' => 'Lax',
352
]);
353
}
354
if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
355
$_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL;
356
}
357
}
358
359
if (!defined('ALLIANTIES_NO_SESSION')) {
360
startAlliantiesSession();
361
}
@@ -0,0 +1,361 @@1
<?php2
declare(strict_types=1);3
4
const ALLIANTIES_SESSION_TTL = 86400 * 30;5
const ALLIANTIES_DEFAULT_AUTH = 'https://auth.timfalken.com';6
const ALLIANTIES_DEFAULT_CLIENT_ID = 'projects.timfalken.com';7
const ALLIANTIES_DEFAULT_BASE = 'https://projects.timfalken.com/allianties';8
const ALLIANTIES_TEST_USERS = 8;9
10
function dataDir(): string11
{12
$override = getenv('ALLIANTIES_DATA_DIR');13
if (is_string($override) && $override !== '') {14
return rtrim($override, '/');15
}16
return dirname(__DIR__) . '/data';17
}18
19
function ensureDataDir(): string20
{21
$dir = dataDir();22
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {23
throw new RuntimeException('De datamap moet schrijfbaar zijn.');24
}25
$deny = $dir . '/.htaccess';26
if (!is_file($deny)) {27
@file_put_contents($deny, "Require all denied\n");28
}29
$sessions = $dir . '/sessions';30
if (!is_dir($sessions)) {31
@mkdir($sessions, 0775, true);32
}33
return $dir;34
}35
36
function localDev(): bool37
{38
$host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);39
return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)40
&& in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);41
}42
43
function config(): array44
{45
$dir = ensureDataDir();46
$path = $dir . '/config.php';47
$lock = fopen($dir . '/config.lock', 'c');48
if ($lock === false) {49
throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');50
}51
try {52
if (!flock($lock, LOCK_EX)) {53
throw new RuntimeException('De configuratie kon niet worden vergrendeld.');54
}55
if (!is_file($path)) {56
$template = <<<'PHP'57
<?php58
// Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.59
// Productie-URL: https://projects.timfalken.com/allianties60
// client_id is het geregistreerde domein: projects.timfalken.com.61
// Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim62
// van dit domein; NIET opnieuw genereren, dat breekt de andere sites).63
// Voeg daar ook het callback-pad /allianties/callback.php toe.64
// Dit bestand wordt niet gedeployed en staat niet in git.65
return [66
'auth_url' => 'https://auth.timfalken.com',67
'base_url' => 'https://projects.timfalken.com/allianties',68
'client_id' => 'projects.timfalken.com',69
'client_secret' => '',70
];71
PHP;72
if (file_put_contents($path, $template) !== strlen($template)) {73
throw new RuntimeException('data/config.php kon niet worden gemaakt.');74
}75
}76
$values = require $path;77
if (!is_array($values)) {78
throw new RuntimeException('data/config.php moet een array teruggeven.');79
}80
} finally {81
flock($lock, LOCK_UN);82
fclose($lock);83
}84
foreach ([85
'auth_url' => 'ALLIANTIES_AUTH_URL',86
'base_url' => 'ALLIANTIES_BASE_URL',87
'client_id' => 'ALLIANTIES_CLIENT_ID',88
'client_secret' => 'ALLIANTIES_CLIENT_SECRET',89
] as $key => $env) {90
if (($values[$key] ?? '') === '') {91
$values[$key] = getenv($env) ?: '';92
}93
}94
if (($values['auth_url'] ?? '') === '') {95
$values['auth_url'] = ALLIANTIES_DEFAULT_AUTH;96
}97
if (($values['client_id'] ?? '') === '') {98
$values['client_id'] = ALLIANTIES_DEFAULT_CLIENT_ID;99
}100
return $values;101
}102
103
function authConfigured(): bool104
{105
$c = config();106
return ($c['client_secret'] ?? '') !== ''107
&& ($c['client_id'] ?? '') !== ''108
&& ($c['base_url'] ?? '') !== '';109
}110
111
function baseUrl(): string112
{113
if (localDev()) {114
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');115
if ($dir === '/' || $dir === '.') {116
$dir = '';117
}118
return 'http://' . $_SERVER['HTTP_HOST'] . $dir;119
}120
$base = rtrim((string) (config()['base_url'] ?? ''), '/');121
if (!str_starts_with($base, 'https://')) {122
throw new RuntimeException(123
"Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "124
. '(https://projects.timfalken.com/allianties), of zet ALLIANTIES_BASE_URL.'125
);126
}127
return $base;128
}129
130
function authUrl(): string131
{132
$url = rtrim((string) (config()['auth_url'] ?? ALLIANTIES_DEFAULT_AUTH), '/');133
return $url !== '' ? $url : ALLIANTIES_DEFAULT_AUTH;134
}135
136
function authRequest(string $path, ?array $form = null, ?string $token = null): array137
{138
$ch = curl_init(authUrl() . $path);139
$headers = ['Accept: application/json', 'User-Agent: Allianties/1.0'];140
if ($token) {141
$headers[] = 'Authorization: Bearer ' . $token;142
}143
curl_setopt_array($ch, [144
CURLOPT_RETURNTRANSFER => true,145
CURLOPT_TIMEOUT => 15,146
CURLOPT_HTTPHEADER => $headers,147
]);148
if ($form !== null) {149
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);150
}151
$body = curl_exec($ch);152
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);153
$err = curl_error($ch);154
curl_close($ch);155
$data = is_string($body) ? json_decode($body, true) : null;156
if ($status !== 200 || !is_array($data)) {157
$hint = $err !== '' ? ' (' . $err . ')' : '';158
throw new RuntimeException(159
'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint160
);161
}162
return $data;163
}164
165
/** @return array{0:string,1:string,2:?string} id, name, avatar */166
function authIdentity(array $profile): array167
{168
if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {169
throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');170
}171
$raw = $profile['id'];172
$numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));173
if (!$numeric || (int) $raw < 1) {174
throw new RuntimeException('Ongeldig account-id.');175
}176
$id = (int) $raw;177
$avatar = null;178
foreach (['avatar_url', 'avatar', 'picture', 'icon', 'image'] as $k) {179
if (isset($profile[$k]) && is_string($profile[$k]) && str_starts_with($profile[$k], 'https://')) {180
$avatar = $profile[$k];181
break;182
}183
}184
if ($avatar === null) {185
$avatar = authUrl() . '/avatar/' . $id;186
}187
return ['auth:' . $id, $profile['username'], $avatar];188
}189
190
function isValidUserId(string $id): bool191
{192
if (preg_match('/^auth:[1-9][0-9]{0,17}$/', $id)) {193
return true;194
}195
return (bool) preg_match('/^local:test_user_([1-9]|1[0-6])$/', $id);196
}197
198
function loginUser(string $id, string $name, ?string $avatar = null): void199
{200
if (!isValidUserId($id)) {201
throw new RuntimeException('Ongeldig account.');202
}203
$name = trim($name);204
if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {205
throw new RuntimeException('Ongeldige gebruikersnaam.');206
}207
session_regenerate_id(true);208
$_SESSION['user'] = $id;209
$_SESSION['name'] = $name;210
$_SESSION['avatar'] = $avatar;211
$_SESSION['csrf'] = bin2hex(random_bytes(24));212
$_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL;213
}214
215
function logoutUser(): void216
{217
$_SESSION = [];218
if (ini_get('session.use_cookies')) {219
$p = session_get_cookie_params();220
setcookie(session_name(), '', [221
'expires' => time() - 3600,222
'path' => $p['path'] ?? '/',223
'secure' => (bool) ($p['secure'] ?? false),224
'httponly' => true,225
'samesite' => 'Lax',226
]);227
}228
session_destroy();229
}230
231
function currentUser(): ?array232
{233
$id = $_SESSION['user'] ?? null;234
$name = $_SESSION['name'] ?? null;235
if (!is_string($id) || $id === '' || !is_string($name)) {236
return null;237
}238
if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {239
return null;240
}241
$avatar = $_SESSION['avatar'] ?? null;242
return [243
'id' => $id,244
'name' => $name,245
'avatar' => is_string($avatar) ? $avatar : null,246
];247
}248
249
function requireUser(): array250
{251
$u = currentUser();252
if (!$u) {253
jsonFail('login', 401);254
}255
return $u;256
}257
258
function csrfToken(): string259
{260
if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {261
$_SESSION['csrf'] = bin2hex(random_bytes(24));262
}263
return $_SESSION['csrf'];264
}265
266
function requireCsrf(): void267
{268
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {269
return;270
}271
$got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';272
if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {273
jsonFail('csrf', 403);274
}275
}276
277
function jsonOut(array $data, int $status = 200): never278
{279
http_response_code($status);280
header('Content-Type: application/json; charset=utf-8');281
header('Cache-Control: no-store');282
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);283
exit;284
}285
286
function jsonFail(string $message, int $status = 400): never287
{288
jsonOut(['ok' => false, 'error' => $message], $status);289
}290
291
function readJsonBody(): array292
{293
$raw = file_get_contents('php://input');294
if (!is_string($raw) || $raw === '') {295
return $_POST;296
}297
$data = json_decode($raw, true);298
return is_array($data) ? $data : [];299
}300
301
function safeNext(mixed $next): ?string302
{303
if (!is_string($next) || $next === '') {304
return null;305
}306
// Only a relative path on this app, no scheme, no protocol-relative, no backslash.307
if (preg_match('#^[a-z]+://#i', $next) || str_starts_with($next, '//') || str_contains($next, '\\')) {308
return null;309
}310
if ($next[0] === '/') {311
return null;312
}313
if (!preg_match('@^[A-Za-z0-9._~/?\#=&%\-]+$@', $next)) {314
return null;315
}316
return $next;317
}318
319
function startAlliantiesSession(): void320
{321
if (session_status() === PHP_SESSION_ACTIVE) {322
return;323
}324
$dir = ensureDataDir() . '/sessions';325
if (!is_dir($dir)) {326
@mkdir($dir, 0775, true);327
}328
session_name('allianties_session');329
ini_set('session.use_strict_mode', '1');330
ini_set('session.gc_maxlifetime', (string) ALLIANTIES_SESSION_TTL);331
session_save_path($dir);332
$path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';333
if ($path === '//') {334
$path = '/';335
}336
$secure = !localDev();337
session_set_cookie_params([338
'lifetime' => ALLIANTIES_SESSION_TTL,339
'path' => $path,340
'secure' => $secure,341
'httponly' => true,342
'samesite' => 'Lax',343
]);344
session_start();345
if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {346
setcookie(session_name(), session_id(), [347
'expires' => time() + ALLIANTIES_SESSION_TTL,348
'path' => $path,349
'secure' => $secure,350
'httponly' => true,351
'samesite' => 'Lax',352
]);353
}354
if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {355
$_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL;356
}357
}358
359
if (!defined('ALLIANTIES_NO_SESSION')) {360
startAlliantiesSession();361
}@@ -0,0 +1,1989 @@
1
{
2
"localeIds": [
3
"en",
4
"nl",
5
"de",
6
"fr",
7
"ja",
8
"zh",
9
"ko",
10
"pl",
11
"ru",
12
"es"
13
],
14
"locales": {
15
"en": {
16
"app.name": "Allianties",
17
"menu.tagline": "A game of patience, alliances and well-timed shots.",
18
"menu.login": "Log in",
19
"menu.logout": "Log out",
20
"menu.loggedInAs": "Logged in as",
21
"menu.localTest": "local test:",
22
"menu.create": "New lobby",
23
"menu.join": "Join",
24
"menu.codePlaceholder": "Code",
25
"menu.myGames": "Your games",
26
"menu.noGames": "You have no games yet. Start a lobby and invite others.",
27
"menu.authUnconfiguredHtml": "Sign-in is not set up on this server yet. The callback <code>/allianties/callback.php</code> must be registered at auth.timfalken.com, and the client secret must be configured.",
28
"menu.guestHint": "Log in to create a lobby, invite players and start a lasting game.",
29
"menu.open": "Open",
30
"menu.continue": "Continue",
31
"menu.statusLobby": "Lobby",
32
"menu.statusRunning": "In play",
33
"menu.statusFinished": "Finished",
34
"menu.youWon": "You won",
35
"menu.draw": "Draw",
36
"menu.winnerIs": "Winner: {name}",
37
"menu.needLogin": "Log in first to play.",
38
"menu.players": "Players",
39
"lobby.title": "Lobby",
40
"lobby.invite": "Invite",
41
"lobby.copy": "Copy link",
42
"lobby.copied": "Copied",
43
"lobby.shareHint": "Share this code or link. Players log in and join.",
44
"lobby.players": "Players",
45
"lobby.start": "Start game",
46
"lobby.leave": "Leave lobby",
47
"lobby.host": "Host",
48
"lobby.you": "you",
49
"lobby.minPlayers": "You need at least two players to start.",
50
"lobby.needTwo": "Waiting for at least one more player…",
51
"lobby.rules": "Rules",
52
"lobby.jury": "Jury",
53
"lobby.juryHint": "Dead players vote each day for a living player. The player with the most votes receives one extra action point at the next daily distribution. Ties: every tied player receives the bonus. Votes are secret and can be changed until then.",
54
"lobby.shrink": "Shrinking arena",
55
"lobby.shrinkHint": "After every set number of days, the outer ring becomes impassable at the daily distribution. Players standing on it lose one life and are pushed inward.",
56
"lobby.shrinkDays": "Days between shrinks",
57
"lobby.shrinkDaysHint": "First shrink after this many midnights, then again each time that many days pass, until the arena reaches its minimum size.",
58
"lobby.ceasefire": "Forced cease-fire hours",
59
"lobby.ceasefireHint": "During these hours (Europe/Amsterdam) no one may shoot. Moving, giving action points and upgrading range remain allowed. Periods may wrap around midnight.",
60
"lobby.ceasefireAdd": "Add period",
61
"lobby.ceasefireRemove": "Remove",
62
"lobby.ceasefireStart": "From",
63
"lobby.ceasefireEnd": "Until",
64
"lobby.ceasefireEmpty": "No periods yet. Add one, or drag a slice on the clock.",
65
"lobby.ceasefireClock": "24-hour clock. Drag the handles or paint a slice; red is cease-fire, gold is open fire. Times are Europe/Amsterdam.",
66
"lobby.apLoot": "Loot action points on a kill",
67
"lobby.apLootHint": "When you eliminate a player with a shot, you receive their remaining action points. Surrender and the shrinking arena do not transfer points. Off by default.",
68
"lobby.apTime": "Daily action points at",
69
"lobby.apTimeHint": "Europe/Amsterdam. Action points, jury awards and arena shrinks all happen at this time each day. Default 00:00.",
70
"lobby.visibility": "Visibility",
71
"lobby.visibilityHint": "Who can see what. You always see your own lives, action points and range. Movement is always public. The server hides everything else from each viewer; hidden events do not appear on the timeline at all.",
72
"lobby.visShots": "Shots",
73
"lobby.visShotsPublic": "Public",
74
"lobby.visShotsElimPublic": "Only eliminating shots are public",
75
"lobby.visShotsKnownTarget": "Known to the target",
76
"lobby.visShotsElimKnownTarget": "Only eliminating shots are known to the target",
77
"lobby.visGifts": "Gifts",
78
"lobby.visGiftsPublic": "Public",
79
"lobby.visGiftsKnownRecipient": "Known to the recipient",
80
"lobby.visGiftsAnonymous": "Anonymous — the recipient gets the points but must deduce who gave them",
81
"lobby.visAp": "Action-point totals",
82
"lobby.visApPublic": "Public",
83
"lobby.visApHidden": "Hidden",
84
"lobby.visRange": "Range",
85
"lobby.visRangePublic": "Public",
86
"lobby.visRangeInRange": "Known to players within range",
87
"lobby.visRangeHidden": "Hidden",
88
"lobby.visLives": "Lives",
89
"lobby.visLivesPublic": "Public",
90
"lobby.visLivesHidden": "Hidden",
91
"info.hidden": "Hidden",
92
"lobby.waiting": "Waiting for the host to start the game.",
93
"lobby.back": "Back",
94
"lobby.code": "Code",
95
"lobby.playerCount.one": "{n} player",
96
"lobby.playerCount.other": "{n} players",
97
"lobby.playerCount.few": "{n} players",
98
"lobby.playerCount.many": "{n} players",
99
"game.day": "Day {n}",
100
"game.nextAp": "Next action points",
101
"game.lives": "Lives",
102
"game.ap": "Action points",
103
"game.range": "Range",
104
"game.you": "You",
105
"game.dead": "Out",
106
"game.surrendered": "Surrendered",
107
"game.winner": "{name} wins!",
108
"game.youWin": "You win!",
109
"game.draw": "The game ends in a draw.",
110
"game.shrinkIn": "Arena shrinks in {n} days",
111
"game.shrinkInDays.one": "Arena shrinks in {n} day",
112
"game.shrinkInDays.other": "Arena shrinks in {n} days",
113
"game.shrinkInDays.few": "Arena shrinks in {n} days",
114
"game.shrinkInDays.many": "Arena shrinks in {n} days",
115
"game.shrinkTomorrow": "Arena shrinks tomorrow",
116
"game.shrinkToday": "Arena shrinks at the next distribution",
117
"game.upgrade": "Upgrade range",
118
"game.settings": "Settings",
119
"game.surrender": "Surrender",
120
"game.surrenderConfirm": "Surrender? You will be out of this game. This cannot be undone.",
121
"game.surrenderConfirmBtn": "Yes, surrender",
122
"game.surrenderCancel": "Cancel",
123
"game.back": "Back to menu",
124
"game.spectating": "You are out. You can still watch, send messages and, if the jury is on, vote.",
125
"game.ceasefireLeft": "Time left in cease-fire",
126
"game.ceasefireUntil": "Time until cease-fire",
127
"game.ceasefireActive": "Cease-fire",
128
"game.attackDisabled": "Attack",
129
"game.attackDisabledReason": "Attack is not allowed during cease-fire hours.",
130
"game.selectSelf": "Your tank is selected. Tap a highlighted tile to move, or upgrade your range.",
131
"game.impassable": "Impassable",
132
"game.willShrink": "This ring will shrink next",
133
"opt.info": "Info",
134
"opt.attack": "Attack",
135
"opt.give": "Give action points",
136
"opt.message": "Send message",
137
"opt.close": "Close",
138
"info.title": "Info",
139
"info.lives": "Lives",
140
"info.ap": "Action points",
141
"info.range": "Range",
142
"info.notes": "Your private notes",
143
"info.notesHint": "Only you can see these notes. They are stored with your account.",
144
"info.saveNotes": "Save notes",
145
"info.saved": "Saved",
146
"give.title": "Give action points",
147
"give.howMany": "How many?",
148
"give.send": "Give",
149
"give.youHave": "You have {n}.",
150
"chat.title": "Message {name}",
151
"chat.placeholder": "Write a private message…",
152
"chat.send": "Send",
153
"chat.empty": "No messages yet.",
154
"jury.title": "Jury",
155
"jury.hint": "Vote for one living player. The player with the most votes gets an extra action point at the next distribution. You can change your vote until then. Other players cannot see your vote.",
156
"jury.vote": "Vote",
157
"jury.votedFor": "You voted for {name}",
158
"jury.change": "Change vote",
159
"timeline.play": "Play",
160
"timeline.pause": "Pause",
161
"timeline.live": "Live",
162
"timeline.stepBack": "Step back",
163
"timeline.stepForward": "Step forward",
164
"timeline.event.start": "The game begins",
165
"timeline.event.move": "{name} moves",
166
"timeline.event.shoot": "{name} shoots {target}",
167
"timeline.event.give": "{name} gives {n} action point(s) to {target}",
168
"timeline.event.upgrade": "{name} upgrades range to {n}",
169
"timeline.event.surrender": "{name} surrenders",
170
"timeline.event.daily": "Day {n}: action points are distributed",
171
"timeline.event.jury": "The jury awards a bonus to {name}",
172
"timeline.event.juryTie": "The jury awards a bonus to {names}",
173
"timeline.event.shrink": "The arena shrinks",
174
"timeline.event.win": "{name} wins",
175
"timeline.event.death": "{name} is out",
176
"timeline.event.deathShot": "{name} is shot by {by}",
177
"timeline.event.deathShrink": "{name} is caught by the shrinking arena",
178
"timeline.event.deathCrushed": "{name} is crushed: no free tile left",
179
"timeline.event.draw": "The game ends in a draw",
180
"auth.unavailable": "Sign-in is temporarily unavailable.",
181
"auth.backToGame": "Back to Allianties",
182
"auth.failed": "Sign-in failed.",
183
"auth.retry": "Try again",
184
"auth.back": "Back",
185
"lang.choose": "Choose language",
186
"lang.current": "Language: {name}",
187
"error.login": "Log in to continue.",
188
"error.csrf": "Your session expired. Refresh the page and try again.",
189
"error.not_host": "Only the host can do that.",
190
"error.min_players": "You need at least two players to start.",
191
"error.not_in_game": "You are not in this game.",
192
"error.dead": "You are out of this game.",
193
"error.no_ap": "You have no action points left.",
194
"error.occupied": "That tile is occupied.",
195
"error.impassable": "That tile is impassable.",
196
"error.out_of_range": "That player is out of range.",
197
"error.invalid_move": "That move is not allowed.",
198
"error.game_started": "This game has already started.",
199
"error.game_finished": "This game is over.",
200
"error.lobby_full": "This lobby is full.",
201
"error.unknown_code": "No lobby found with that code.",
202
"error.cannot_vote": "You cannot vote now.",
203
"error.bad_vote": "You can only vote for a living player.",
204
"error.bad_give": "You cannot give that many action points.",
205
"error.unknown_action": "Unknown action.",
206
"error.ceasefire": "You cannot attack during cease-fire hours.",
207
"error.generic": "Something went wrong. Please try again.",
208
"error.serverStatus": "The server returned {status}."
209
},
210
"nl": {
211
"app.name": "Allianties",
212
"menu.tagline": "Een spel van geduld, allianties en goed getimede schoten.",
213
"menu.login": "Inloggen",
214
"menu.logout": "Uitloggen",
215
"menu.loggedInAs": "Ingelogd als",
216
"menu.localTest": "lokale test:",
217
"menu.create": "Nieuwe lobby",
218
"menu.join": "Deelnemen",
219
"menu.codePlaceholder": "Code",
220
"menu.myGames": "Jouw spellen",
221
"menu.noGames": "Je hebt nog geen spellen. Start een lobby en nodig anderen uit.",
222
"menu.authUnconfiguredHtml": "Inloggen is op deze server nog niet ingesteld. De callback <code>/allianties/callback.php</code> moet bij auth.timfalken.com worden geregistreerd, en het clientgeheim moet worden gezet.",
223
"menu.guestHint": "Log in om een lobby te maken, spelers uit te nodigen en een blijvend spel te starten.",
224
"menu.open": "Openen",
225
"menu.continue": "Verder",
226
"menu.statusLobby": "Lobby",
227
"menu.statusRunning": "Bezig",
228
"menu.statusFinished": "Afgelopen",
229
"menu.youWon": "Jij won",
230
"menu.draw": "Gelijkspel",
231
"menu.winnerIs": "Winnaar: {name}",
232
"menu.needLogin": "Log eerst in om te spelen.",
233
"menu.players": "Spelers",
234
"lobby.title": "Lobby",
235
"lobby.invite": "Uitnodigen",
236
"lobby.copy": "Kopieer link",
237
"lobby.copied": "Gekopieerd",
238
"lobby.shareHint": "Deel deze code of link. Spelers loggen in en doen mee.",
239
"lobby.players": "Spelers",
240
"lobby.start": "Start spel",
241
"lobby.leave": "Lobby verlaten",
242
"lobby.host": "Host",
243
"lobby.you": "jij",
244
"lobby.minPlayers": "Je hebt minstens twee spelers nodig om te starten.",
245
"lobby.needTwo": "Wachten op minstens één speler extra…",
246
"lobby.rules": "Regels",
247
"lobby.jury": "Jury",
248
"lobby.juryHint": "Dode spelers stemmen elke dag op een levende speler. Wie de meeste stemmen krijgt, ontvangt één extra actiepunt bij de volgende dagelijkse uitdeling. Bij een gelijke stand krijgt iedere gelijkstaande speler de bonus. Stemmen zijn geheim en tot dan toe te wijzigen.",
249
"lobby.shrink": "Krimpend speelveld",
250
"lobby.shrinkHint": "Na elk ingesteld aantal dagen wordt de buitenste ring bij de dagelijkse uitdeling onbegaanbaar. Spelers die erop staan verliezen een leven en worden naar binnen geduwd.",
251
"lobby.shrinkDays": "Dagen tussen krimp",
252
"lobby.shrinkDaysHint": "De eerste krimp na dit aantal middernachten, daarna opnieuw telkens na evenveel dagen, tot het veld zijn minimumgrootte heeft.",
253
"lobby.ceasefire": "Gedwongen staakt-het-vuren",
254
"lobby.ceasefireHint": "In deze uren (Europe/Amsterdam) mag niemand schieten. Verplaatsen, actiepunten geven en bereik upgraden blijft toegestaan. Periodes mogen over middernacht lopen.",
255
"lobby.ceasefireAdd": "Periode toevoegen",
256
"lobby.ceasefireRemove": "Verwijderen",
257
"lobby.ceasefireStart": "Van",
258
"lobby.ceasefireEnd": "Tot",
259
"lobby.ceasefireEmpty": "Nog geen periodes. Voeg er een toe, of sleep een stuk op de klok.",
260
"lobby.ceasefireClock": "24-uursklok. Sleep de handvatten of teken een stuk; rood is staakt-het-vuren, goud is vrij schieten. Tijden zijn Europe/Amsterdam.",
261
"lobby.apLoot": "Actiepunten plunderen bij een kill",
262
"lobby.apLootHint": "Als je een speler uitschakelt met een schot, ontvang je diens resterende actiepunten. Overgave en het krimpende speelveld geven geen punten. Standaard uit.",
263
"lobby.apTime": "Dagelijkse actiepunten om",
264
"lobby.apTimeHint": "Europe/Amsterdam. Actiepunten, jurybonussen en het krimpen van het veld gebeuren elke dag op dit tijdstip. Standaard 00:00.",
265
"lobby.visibility": "Zichtbaarheid",
266
"lobby.visibilityHint": "Wie wat kan zien. Je ziet altijd je eigen levens, actiepunten en bereik. Verplaatsingen zijn altijd openbaar. De server verbergt de rest per kijker; verborgen gebeurtenissen verschijnen helemaal niet op de tijdlijn.",
267
"lobby.visShots": "Schoten",
268
"lobby.visShotsPublic": "Openbaar",
269
"lobby.visShotsElimPublic": "Alleen uitschakelende schoten zijn openbaar",
270
"lobby.visShotsKnownTarget": "Alleen bekend bij het doelwit",
271
"lobby.visShotsElimKnownTarget": "Alleen een uitschakelend schot is bekend bij het doelwit",
272
"lobby.visGifts": "Giften",
273
"lobby.visGiftsPublic": "Openbaar",
274
"lobby.visGiftsKnownRecipient": "Alleen bekend bij de ontvanger",
275
"lobby.visGiftsAnonymous": "Anoniem — de ontvanger krijgt de punten maar moet zelf afleiden van wie",
276
"lobby.visAp": "Actiepuntentotalen",
277
"lobby.visApPublic": "Openbaar",
278
"lobby.visApHidden": "Verborgen",
279
"lobby.visRange": "Bereik",
280
"lobby.visRangePublic": "Openbaar",
281
"lobby.visRangeInRange": "Bekend bij spelers binnen bereik",
282
"lobby.visRangeHidden": "Verborgen",
283
"lobby.visLives": "Levens",
284
"lobby.visLivesPublic": "Openbaar",
285
"lobby.visLivesHidden": "Verborgen",
286
"info.hidden": "Verborgen",
287
"lobby.waiting": "Wachten tot de host het spel start.",
288
"lobby.back": "Terug",
289
"lobby.code": "Code",
290
"lobby.playerCount.one": "{n} speler",
291
"lobby.playerCount.other": "{n} spelers",
292
"lobby.playerCount.few": "{n} spelers",
293
"lobby.playerCount.many": "{n} spelers",
294
"game.day": "Dag {n}",
295
"game.nextAp": "Volgende actiepunten",
296
"game.lives": "Levens",
297
"game.ap": "Actiepunten",
298
"game.range": "Bereik",
299
"game.you": "Jij",
300
"game.dead": "Uitgeschakeld",
301
"game.surrendered": "Overgegeven",
302
"game.winner": "{name} wint!",
303
"game.youWin": "Jij wint!",
304
"game.draw": "Het spel eindigt in een gelijkspel.",
305
"game.shrinkIn": "Het veld krimpt over {n} dagen",
306
"game.shrinkInDays.one": "Het veld krimpt over {n} dag",
307
"game.shrinkInDays.other": "Het veld krimpt over {n} dagen",
308
"game.shrinkInDays.few": "Het veld krimpt over {n} dagen",
309
"game.shrinkInDays.many": "Het veld krimpt over {n} dagen",
310
"game.shrinkTomorrow": "Het veld krimpt morgen",
311
"game.shrinkToday": "Het veld krimpt bij de volgende uitdeling",
312
"game.upgrade": "Bereik vergroten",
313
"game.settings": "Instellingen",
314
"game.surrender": "Overgeven",
315
"game.surrenderConfirm": "Overgeven? Je bent dan uit dit spel. Dit kun je niet ongedaan maken.",
316
"game.surrenderConfirmBtn": "Ja, overgeven",
317
"game.surrenderCancel": "Annuleren",
318
"game.back": "Terug naar het menu",
319
"game.spectating": "Je bent uitgeschakeld. Je kunt nog meekijken, berichten sturen en, als de jury aan staat, stemmen.",
320
"game.ceasefireLeft": "Tijd over in het staakt-het-vuren",
321
"game.ceasefireUntil": "Tijd tot het staakt-het-vuren",
322
"game.ceasefireActive": "Staakt-het-vuren",
323
"game.attackDisabled": "Aanvallen",
324
"game.attackDisabledReason": "Aanvallen is niet toegestaan tijdens het staakt-het-vuren.",
325
"game.selectSelf": "Jouw tank is geselecteerd. Tik op een gemarkeerd vakje om te bewegen, of vergroot je bereik.",
326
"game.impassable": "Onbegaanbaar",
327
"game.willShrink": "Deze ring krimpt als volgende",
328
"opt.info": "Info",
329
"opt.attack": "Aanvallen",
330
"opt.give": "Actiepunten geven",
331
"opt.message": "Bericht sturen",
332
"opt.close": "Sluiten",
333
"info.title": "Info",
334
"info.lives": "Levens",
335
"info.ap": "Actiepunten",
336
"info.range": "Bereik",
337
"info.notes": "Jouw privénotities",
338
"info.notesHint": "Alleen jij ziet deze notities. Ze worden bij jouw account bewaard.",
339
"info.saveNotes": "Notities opslaan",
340
"info.saved": "Opgeslagen",
341
"give.title": "Actiepunten geven",
342
"give.howMany": "Hoeveel?",
343
"give.send": "Geven",
344
"give.youHave": "Je hebt er {n}.",
345
"chat.title": "Bericht aan {name}",
346
"chat.placeholder": "Schrijf een privébericht…",
347
"chat.send": "Versturen",
348
"chat.empty": "Nog geen berichten.",
349
"jury.title": "Jury",
350
"jury.hint": "Stem op één levende speler. Wie de meeste stemmen krijgt, ontvangt een extra actiepunt bij de volgende uitdeling. Je kunt je stem tot dan toe wijzigen. Andere spelers zien je stem niet.",
351
"jury.vote": "Stemmen",
352
"jury.votedFor": "Je stemde op {name}",
353
"jury.change": "Stem wijzigen",
354
"timeline.play": "Afspelen",
355
"timeline.pause": "Pauzeren",
356
"timeline.live": "Live",
357
"timeline.stepBack": "Een stap terug",
358
"timeline.stepForward": "Een stap vooruit",
359
"timeline.event.start": "Het spel begint",
360
"timeline.event.move": "{name} verplaatst zich",
361
"timeline.event.shoot": "{name} schiet op {target}",
362
"timeline.event.give": "{name} geeft {n} actiepunt(en) aan {target}",
363
"timeline.event.upgrade": "{name} vergroot het bereik naar {n}",
364
"timeline.event.surrender": "{name} geeft zich over",
365
"timeline.event.daily": "Dag {n}: actiepunten worden uitgedeeld",
366
"timeline.event.jury": "De jury kent een bonus toe aan {name}",
367
"timeline.event.juryTie": "De jury kent een bonus toe aan {names}",
368
"timeline.event.shrink": "Het speelveld krimpt",
369
"timeline.event.win": "{name} wint",
370
"timeline.event.death": "{name} is uitgeschakeld",
371
"timeline.event.deathShot": "{name} wordt neergeschoten door {by}",
372
"timeline.event.deathShrink": "{name} wordt geraakt door het krimpende veld",
373
"timeline.event.deathCrushed": "{name} wordt vermorzeld: geen vrij vakje meer",
374
"timeline.event.draw": "Het spel eindigt in een gelijkspel",
375
"auth.unavailable": "Inloggen is tijdelijk niet beschikbaar.",
376
"auth.backToGame": "Terug naar Allianties",
377
"auth.failed": "Inloggen is mislukt.",
378
"auth.retry": "Opnieuw proberen",
379
"auth.back": "Terug",
380
"lang.choose": "Kies een taal",
381
"lang.current": "Taal: {name}",
382
"error.login": "Log in om verder te gaan.",
383
"error.csrf": "Je sessie is verlopen. Vernieuw de pagina en probeer het opnieuw.",
384
"error.not_host": "Alleen de host kan dat doen.",
385
"error.min_players": "Je hebt minstens twee spelers nodig om te starten.",
386
"error.not_in_game": "Je zit niet in dit spel.",
387
"error.dead": "Je bent uit dit spel.",
388
"error.no_ap": "Je hebt geen actiepunten meer.",
389
"error.occupied": "Dat vakje is bezet.",
390
"error.impassable": "Dat vakje is onbegaanbaar.",
391
"error.out_of_range": "Die speler is buiten bereik.",
392
"error.invalid_move": "Die zet is niet toegestaan.",
393
"error.game_started": "Dit spel is al begonnen.",
394
"error.game_finished": "Dit spel is afgelopen.",
395
"error.lobby_full": "Deze lobby is vol.",
396
"error.unknown_code": "Geen lobby gevonden met die code.",
397
"error.cannot_vote": "Je kunt nu niet stemmen.",
398
"error.bad_vote": "Je kunt alleen op een levende speler stemmen.",
399
"error.bad_give": "Zoveel actiepunten kun je niet geven.",
400
"error.unknown_action": "Onbekende actie.",
401
"error.ceasefire": "Je kunt niet aanvallen tijdens het staakt-het-vuren.",
402
"error.generic": "Er ging iets mis. Probeer het opnieuw.",
403
"error.serverStatus": "De server gaf {status}."
404
},
405
"de": {
406
"app.name": "Allianties",
407
"menu.tagline": "Ein Spiel aus Geduld, Allianzen und gut getimten Schüssen.",
408
"menu.login": "Anmelden",
409
"menu.logout": "Abmelden",
410
"menu.loggedInAs": "Angemeldet als",
411
"menu.localTest": "lokaler Test:",
412
"menu.create": "Neue Lobby",
413
"menu.join": "Beitreten",
414
"menu.codePlaceholder": "Code",
415
"menu.myGames": "Deine Spiele",
416
"menu.noGames": "Du hast noch keine Spiele. Eröffne eine Lobby und lade andere ein.",
417
"menu.authUnconfiguredHtml": "Die Anmeldung ist auf diesem Server noch nicht eingerichtet. Der Callback <code>/allianties/callback.php</code> muss bei auth.timfalken.com registriert und das Client-Geheimnis konfiguriert werden.",
418
"menu.guestHint": "Melde dich an, um eine Lobby zu erstellen, Spieler einzuladen und ein dauerhaftes Spiel zu starten.",
419
"menu.open": "Öffnen",
420
"menu.continue": "Weiter",
421
"menu.statusLobby": "Lobby",
422
"menu.statusRunning": "Läuft",
423
"menu.statusFinished": "Beendet",
424
"menu.youWon": "Du hast gewonnen",
425
"menu.draw": "Unentschieden",
426
"menu.winnerIs": "Gewinner: {name}",
427
"menu.needLogin": "Melde dich zuerst an, um zu spielen.",
428
"menu.players": "Spieler",
429
"lobby.title": "Lobby",
430
"lobby.invite": "Einladen",
431
"lobby.copy": "Link kopieren",
432
"lobby.copied": "Kopiert",
433
"lobby.shareHint": "Teile diesen Code oder Link. Spieler melden sich an und treten bei.",
434
"lobby.players": "Spieler",
435
"lobby.start": "Spiel starten",
436
"lobby.leave": "Lobby verlassen",
437
"lobby.host": "Gastgeber",
438
"lobby.you": "du",
439
"lobby.minPlayers": "Du brauchst mindestens zwei Spieler, um zu starten.",
440
"lobby.needTwo": "Warte auf mindestens einen weiteren Spieler…",
441
"lobby.rules": "Regeln",
442
"lobby.jury": "Jury",
443
"lobby.juryHint": "Tote Spieler stimmen täglich für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten täglichen Verteilung einen Extra-Aktionspunkt. Bei Gleichstand erhält jeder gleichauf liegende Spieler den Bonus. Stimmen sind geheim und bis dahin änderbar.",
444
"lobby.shrink": "Schrumpfendes Spielfeld",
445
"lobby.shrinkHint": "Nach einer festgelegten Anzahl von Tagen wird der äußere Ring bei der täglichen Verteilung unpassierbar. Spieler, die darauf stehen, verlieren ein Leben und werden nach innen geschoben.",
446
"lobby.shrinkDays": "Tage zwischen Schrumpfungen",
447
"lobby.shrinkDaysHint": "Erste Schrumpfung nach so vielen Mitternächten, danach erneut nach jeweils ebenso vielen Tagen, bis das Feld seine Mindestgröße erreicht.",
448
"lobby.ceasefire": "Erzwungene Waffenruhe",
449
"lobby.ceasefireHint": "In diesen Stunden (Europe/Amsterdam) darf niemand schießen. Bewegen, Aktionspunkte abgeben und die Reichweite erhöhen bleiben erlaubt. Zeiträume dürfen über Mitternacht gehen.",
450
"lobby.ceasefireAdd": "Zeitraum hinzufügen",
451
"lobby.ceasefireRemove": "Entfernen",
452
"lobby.ceasefireStart": "Von",
453
"lobby.ceasefireEnd": "Bis",
454
"lobby.ceasefireEmpty": "Noch keine Zeiträume. Füge einen hinzu oder ziehe ein Segment auf der Uhr.",
455
"lobby.ceasefireClock": "24-Stunden-Uhr. Ziehe die Griffe oder male ein Segment; rot ist Waffenruhe, gold ist Feuer frei. Zeiten sind Europe/Amsterdam.",
456
"lobby.apLoot": "Aktionspunkte bei einem Kill erbeuten",
457
"lobby.apLootHint": "Wenn du einen Spieler mit einem Schuss ausschaltest, erhältst du dessen verbleibende Aktionspunkte. Aufgabe und das schrumpfende Feld übertragen keine Punkte. Standardmäßig aus.",
458
"lobby.apTime": "Tägliche Aktionspunkte um",
459
"lobby.apTimeHint": "Europe/Amsterdam. Aktionspunkte, Jury-Boni und das Schrumpfen des Feldes finden jeden Tag zu dieser Uhrzeit statt. Standard 00:00.",
460
"lobby.visibility": "Sichtbarkeit",
461
"lobby.visibilityHint": "Wer was sehen kann. Du siehst immer deine eigenen Leben, Aktionspunkte und Reichweite. Bewegungen sind immer öffentlich. Der Server blendet alles andere je Betrachter aus; versteckte Ereignisse erscheinen gar nicht auf der Zeitleiste.",
462
"lobby.visShots": "Schüsse",
463
"lobby.visShotsPublic": "Öffentlich",
464
"lobby.visShotsElimPublic": "Nur ausschaltende Schüsse sind öffentlich",
465
"lobby.visShotsKnownTarget": "Nur dem Ziel bekannt",
466
"lobby.visShotsElimKnownTarget": "Nur ein ausschaltender Schuss ist dem Ziel bekannt",
467
"lobby.visGifts": "Geschenke",
468
"lobby.visGiftsPublic": "Öffentlich",
469
"lobby.visGiftsKnownRecipient": "Nur dem Empfänger bekannt",
470
"lobby.visGiftsAnonymous": "Anonym — der Empfänger erhält die Punkte, muss den Geber aber selbst ableiten",
471
"lobby.visAp": "Aktionspunkte-Stand",
472
"lobby.visApPublic": "Öffentlich",
473
"lobby.visApHidden": "Verborgen",
474
"lobby.visRange": "Reichweite",
475
"lobby.visRangePublic": "Öffentlich",
476
"lobby.visRangeInRange": "Bekannt für Spieler in Reichweite",
477
"lobby.visRangeHidden": "Verborgen",
478
"lobby.visLives": "Leben",
479
"lobby.visLivesPublic": "Öffentlich",
480
"lobby.visLivesHidden": "Verborgen",
481
"info.hidden": "Verborgen",
482
"lobby.waiting": "Warte, bis der Gastgeber das Spiel startet.",
483
"lobby.back": "Zurück",
484
"lobby.code": "Code",
485
"lobby.playerCount.one": "{n} Spieler",
486
"lobby.playerCount.other": "{n} Spieler",
487
"lobby.playerCount.few": "{n} Spieler",
488
"lobby.playerCount.many": "{n} Spieler",
489
"game.day": "Tag {n}",
490
"game.nextAp": "Nächste Aktionspunkte",
491
"game.lives": "Leben",
492
"game.ap": "Aktionspunkte",
493
"game.range": "Reichweite",
494
"game.you": "Du",
495
"game.dead": "Ausgeschieden",
496
"game.surrendered": "Aufgegeben",
497
"game.winner": "{name} gewinnt!",
498
"game.youWin": "Du gewinnst!",
499
"game.draw": "Das Spiel endet unentschieden.",
500
"game.shrinkIn": "Das Feld schrumpft in {n} Tagen",
501
"game.shrinkInDays.one": "Das Feld schrumpft in {n} Tag",
502
"game.shrinkInDays.other": "Das Feld schrumpft in {n} Tagen",
503
"game.shrinkInDays.few": "Das Feld schrumpft in {n} Tagen",
504
"game.shrinkInDays.many": "Das Feld schrumpft in {n} Tagen",
505
"game.shrinkTomorrow": "Das Feld schrumpft morgen",
506
"game.shrinkToday": "Das Feld schrumpft bei der nächsten Verteilung",
507
"game.upgrade": "Reichweite erhöhen",
508
"game.settings": "Einstellungen",
509
"game.surrender": "Aufgeben",
510
"game.surrenderConfirm": "Aufgeben? Du scheidest aus diesem Spiel aus. Das lässt sich nicht rückgängig machen.",
511
"game.surrenderConfirmBtn": "Ja, aufgeben",
512
"game.surrenderCancel": "Abbrechen",
513
"game.back": "Zurück zum Menü",
514
"game.spectating": "Du bist ausgeschieden. Du kannst weiterhin zuschauen, Nachrichten senden und, wenn die Jury an ist, abstimmen.",
515
"game.ceasefireLeft": "Verbleibende Waffenruhe",
516
"game.ceasefireUntil": "Zeit bis zur Waffenruhe",
517
"game.ceasefireActive": "Waffenruhe",
518
"game.attackDisabled": "Angreifen",
519
"game.attackDisabledReason": "Angreifen ist während der Waffenruhe nicht erlaubt.",
520
"game.selectSelf": "Dein Panzer ist ausgewählt. Tippe auf ein markiertes Feld, um dich zu bewegen, oder erhöhe deine Reichweite.",
521
"game.impassable": "Unpassierbar",
522
"game.willShrink": "Dieser Ring schrumpft als Nächstes",
523
"opt.info": "Info",
524
"opt.attack": "Angreifen",
525
"opt.give": "Aktionspunkte geben",
526
"opt.message": "Nachricht senden",
527
"opt.close": "Schließen",
528
"info.title": "Info",
529
"info.lives": "Leben",
530
"info.ap": "Aktionspunkte",
531
"info.range": "Reichweite",
532
"info.notes": "Deine privaten Notizen",
533
"info.notesHint": "Nur du kannst diese Notizen sehen. Sie werden bei deinem Konto gespeichert.",
534
"info.saveNotes": "Notizen speichern",
535
"info.saved": "Gespeichert",
536
"give.title": "Aktionspunkte geben",
537
"give.howMany": "Wie viele?",
538
"give.send": "Geben",
539
"give.youHave": "Du hast {n}.",
540
"chat.title": "Nachricht an {name}",
541
"chat.placeholder": "Schreibe eine private Nachricht…",
542
"chat.send": "Senden",
543
"chat.empty": "Noch keine Nachrichten.",
544
"jury.title": "Jury",
545
"jury.hint": "Stimme für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten Verteilung einen Extra-Aktionspunkt. Du kannst deine Stimme bis dahin ändern. Andere Spieler sehen deine Stimme nicht.",
546
"jury.vote": "Abstimmen",
547
"jury.votedFor": "Du hast für {name} gestimmt",
548
"jury.change": "Stimme ändern",
549
"timeline.play": "Abspielen",
550
"timeline.pause": "Pause",
551
"timeline.live": "Live",
552
"timeline.stepBack": "Einen Schritt zurück",
553
"timeline.stepForward": "Einen Schritt vor",
554
"timeline.event.start": "Das Spiel beginnt",
555
"timeline.event.move": "{name} bewegt sich",
556
"timeline.event.shoot": "{name} schießt auf {target}",
557
"timeline.event.give": "{name} gibt {n} Aktionspunkt(e) an {target}",
558
"timeline.event.upgrade": "{name} erhöht die Reichweite auf {n}",
559
"timeline.event.surrender": "{name} gibt auf",
560
"timeline.event.daily": "Tag {n}: Aktionspunkte werden verteilt",
561
"timeline.event.jury": "Die Jury vergibt einen Bonus an {name}",
562
"timeline.event.juryTie": "Die Jury vergibt einen Bonus an {names}",
563
"timeline.event.shrink": "Das Spielfeld schrumpft",
564
"timeline.event.win": "{name} gewinnt",
565
"timeline.event.death": "{name} scheidet aus",
566
"timeline.event.deathShot": "{name} wird von {by} erschossen",
567
"timeline.event.deathShrink": "{name} wird vom schrumpfenden Feld erfasst",
568
"timeline.event.deathCrushed": "{name} wird zerdrückt: kein freies Feld mehr",
569
"timeline.event.draw": "Das Spiel endet unentschieden",
570
"auth.unavailable": "Die Anmeldung ist vorübergehend nicht verfügbar.",
571
"auth.backToGame": "Zurück zu Allianties",
572
"auth.failed": "Anmeldung fehlgeschlagen.",
573
"auth.retry": "Erneut versuchen",
574
"auth.back": "Zurück",
575
"lang.choose": "Sprache wählen",
576
"lang.current": "Sprache: {name}",
577
"error.login": "Melde dich an, um fortzufahren.",
578
"error.csrf": "Deine Sitzung ist abgelaufen. Aktualisiere die Seite und versuche es erneut.",
579
"error.not_host": "Das kann nur der Gastgeber tun.",
580
"error.min_players": "Du brauchst mindestens zwei Spieler, um zu starten.",
581
"error.not_in_game": "Du bist nicht in diesem Spiel.",
582
"error.dead": "Du bist aus diesem Spiel ausgeschieden.",
583
"error.no_ap": "Du hast keine Aktionspunkte mehr.",
584
"error.occupied": "Dieses Feld ist besetzt.",
585
"error.impassable": "Dieses Feld ist unpassierbar.",
586
"error.out_of_range": "Dieser Spieler ist außer Reichweite.",
587
"error.invalid_move": "Dieser Zug ist nicht erlaubt.",
588
"error.game_started": "Dieses Spiel hat bereits begonnen.",
589
"error.game_finished": "Dieses Spiel ist beendet.",
590
"error.lobby_full": "Diese Lobby ist voll.",
591
"error.unknown_code": "Keine Lobby mit diesem Code gefunden.",
592
"error.cannot_vote": "Du kannst jetzt nicht abstimmen.",
593
"error.bad_vote": "Du kannst nur für einen lebenden Spieler stimmen.",
594
"error.bad_give": "So viele Aktionspunkte kannst du nicht abgeben.",
595
"error.unknown_action": "Unbekannte Aktion.",
596
"error.ceasefire": "Während der Waffenruhe kannst du nicht angreifen.",
597
"error.generic": "Etwas ist schiefgegangen. Bitte versuche es erneut.",
598
"error.serverStatus": "Der Server antwortete mit {status}."
599
},
600
"fr": {
601
"app.name": "Allianties",
602
"menu.tagline": "Un jeu de patience, d'alliances et de tirs bien calculés.",
603
"menu.login": "Connexion",
604
"menu.logout": "Déconnexion",
605
"menu.loggedInAs": "Connecté en tant que",
606
"menu.localTest": "test local :",
607
"menu.create": "Nouveau salon",
608
"menu.join": "Rejoindre",
609
"menu.codePlaceholder": "Code",
610
"menu.myGames": "Vos parties",
611
"menu.noGames": "Vous n'avez pas encore de partie. Créez un salon et invitez d'autres joueurs.",
612
"menu.authUnconfiguredHtml": "La connexion n'est pas encore configurée sur ce serveur. Le callback <code>/allianties/callback.php</code> doit être enregistré sur auth.timfalken.com, et le secret client doit être défini.",
613
"menu.guestHint": "Connectez-vous pour créer un salon, inviter des joueurs et lancer une partie durable.",
614
"menu.open": "Ouvrir",
615
"menu.continue": "Continuer",
616
"menu.statusLobby": "Salon",
617
"menu.statusRunning": "En cours",
618
"menu.statusFinished": "Terminée",
619
"menu.youWon": "Vous avez gagné",
620
"menu.draw": "Match nul",
621
"menu.winnerIs": "Vainqueur : {name}",
622
"menu.needLogin": "Connectez-vous d'abord pour jouer.",
623
"menu.players": "Joueurs",
624
"lobby.title": "Salon",
625
"lobby.invite": "Inviter",
626
"lobby.copy": "Copier le lien",
627
"lobby.copied": "Copié",
628
"lobby.shareHint": "Partagez ce code ou ce lien. Les joueurs se connectent et rejoignent la partie.",
629
"lobby.players": "Joueurs",
630
"lobby.start": "Lancer la partie",
631
"lobby.leave": "Quitter le salon",
632
"lobby.host": "Hôte",
633
"lobby.you": "vous",
634
"lobby.minPlayers": "Il faut au moins deux joueurs pour commencer.",
635
"lobby.needTwo": "En attente d'au moins un joueur de plus…",
636
"lobby.rules": "Règles",
637
"lobby.jury": "Jury",
638
"lobby.juryHint": "Les joueurs éliminés votent chaque jour pour un joueur vivant. Celui qui recueille le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution quotidienne. En cas d'égalité, chaque joueur à égalité reçoit le bonus. Les votes sont secrets et modifiables jusque-là.",
639
"lobby.shrink": "Arène rétrécissante",
640
"lobby.shrinkHint": "Après un nombre de jours réglable, l'anneau extérieur devient infranchissable à la distribution quotidienne. Les joueurs qui s'y trouvent perdent une vie et sont poussés vers l'intérieur.",
641
"lobby.shrinkDays": "Jours entre les rétrécissements",
642
"lobby.shrinkDaysHint": "Premier rétrécissement après autant de minuits, puis de nouveau tous les autant de jours, jusqu'à la taille minimale de l'arène.",
643
"lobby.ceasefire": "Heures de cessez-le-feu forcé",
644
"lobby.ceasefireHint": "Pendant ces heures (Europe/Amsterdam), personne ne peut tirer. Se déplacer, donner des points d'action et améliorer la portée restent autorisés. Les plages peuvent chevaucher minuit.",
645
"lobby.ceasefireAdd": "Ajouter une plage",
646
"lobby.ceasefireRemove": "Supprimer",
647
"lobby.ceasefireStart": "De",
648
"lobby.ceasefireEnd": "À",
649
"lobby.ceasefireEmpty": "Aucune plage pour l'instant. Ajoutez-en une, ou dessinez un secteur sur l'horloge.",
650
"lobby.ceasefireClock": "Horloge 24 heures. Faites glisser les poignées ou dessinez un secteur ; le rouge est le cessez-le-feu, l'or le feu autorisé. Heures en Europe/Amsterdam.",
651
"lobby.apLoot": "Prendre les points d’action lors d’une élimination",
652
"lobby.apLootHint": "Lorsque vous éliminez un joueur par un tir, vous recevez ses points d’action restants. Abandon et arène qui rétrécit ne transfèrent rien. Désactivé par défaut.",
653
"lobby.apTime": "Points d’action quotidiens à",
654
"lobby.apTimeHint": "Europe/Amsterdam. Les points d’action, les bonus du jury et le rétrécissement ont lieu chaque jour à cette heure. 00:00 par défaut.",
655
"lobby.visibility": "Visibilité",
656
"lobby.visibilityHint": "Qui voit quoi. Vous voyez toujours vos propres vies, points d’action et portée. Les déplacements sont toujours publics. Le serveur masque le reste pour chaque spectateur ; les événements cachés n’apparaissent pas du tout sur la timeline.",
657
"lobby.visShots": "Tirs",
658
"lobby.visShotsPublic": "Public",
659
"lobby.visShotsElimPublic": "Seuls les tirs éliminatoires sont publics",
660
"lobby.visShotsKnownTarget": "Connu de la cible",
661
"lobby.visShotsElimKnownTarget": "Seul un tir éliminatoire est connu de la cible",
662
"lobby.visGifts": "Dons",
663
"lobby.visGiftsPublic": "Public",
664
"lobby.visGiftsKnownRecipient": "Connu du destinataire",
665
"lobby.visGiftsAnonymous": "Anonyme — le destinataire reçoit les points mais doit déduire de qui ils viennent",
666
"lobby.visAp": "Totaux de points d’action",
667
"lobby.visApPublic": "Public",
668
"lobby.visApHidden": "Caché",
669
"lobby.visRange": "Portée",
670
"lobby.visRangePublic": "Public",
671
"lobby.visRangeInRange": "Connu des joueurs à portée",
672
"lobby.visRangeHidden": "Caché",
673
"lobby.visLives": "Vies",
674
"lobby.visLivesPublic": "Public",
675
"lobby.visLivesHidden": "Caché",
676
"info.hidden": "Caché",
677
"lobby.waiting": "En attente que l'hôte lance la partie.",
678
"lobby.back": "Retour",
679
"lobby.code": "Code",
680
"lobby.playerCount.one": "{n} joueur",
681
"lobby.playerCount.other": "{n} joueurs",
682
"lobby.playerCount.few": "{n} joueurs",
683
"lobby.playerCount.many": "{n} joueurs",
684
"game.day": "Jour {n}",
685
"game.nextAp": "Prochains points d'action",
686
"game.lives": "Vies",
687
"game.ap": "Points d'action",
688
"game.range": "Portée",
689
"game.you": "Vous",
690
"game.dead": "Éliminé",
691
"game.surrendered": "A abandonné",
692
"game.winner": "{name} gagne !",
693
"game.youWin": "Vous gagnez !",
694
"game.draw": "La partie se termine par un match nul.",
695
"game.shrinkIn": "L'arène rétrécit dans {n} jours",
696
"game.shrinkInDays.one": "L'arène rétrécit dans {n} jour",
697
"game.shrinkInDays.other": "L'arène rétrécit dans {n} jours",
698
"game.shrinkInDays.few": "L'arène rétrécit dans {n} jours",
699
"game.shrinkInDays.many": "L'arène rétrécit dans {n} jours",
700
"game.shrinkTomorrow": "L'arène rétrécit demain",
701
"game.shrinkToday": "L'arène rétrécit à la prochaine distribution",
702
"game.upgrade": "Augmenter la portée",
703
"game.settings": "Paramètres",
704
"game.surrender": "Abandonner",
705
"game.surrenderConfirm": "Abandonner ? Vous serez éliminé de cette partie. Cette action est irréversible.",
706
"game.surrenderConfirmBtn": "Oui, abandonner",
707
"game.surrenderCancel": "Annuler",
708
"game.back": "Retour au menu",
709
"game.spectating": "Vous êtes éliminé. Vous pouvez encore regarder, envoyer des messages et, si le jury est actif, voter.",
710
"game.ceasefireLeft": "Temps restant de cessez-le-feu",
711
"game.ceasefireUntil": "Temps avant le cessez-le-feu",
712
"game.ceasefireActive": "Cessez-le-feu",
713
"game.attackDisabled": "Attaquer",
714
"game.attackDisabledReason": "Attaquer n'est pas autorisé pendant les heures de cessez-le-feu.",
715
"game.selectSelf": "Votre tank est sélectionné. Touchez une case mise en évidence pour vous déplacer, ou augmentez votre portée.",
716
"game.impassable": "Infranchissable",
717
"game.willShrink": "Cet anneau rétrécira ensuite",
718
"opt.info": "Infos",
719
"opt.attack": "Attaquer",
720
"opt.give": "Donner des points d'action",
721
"opt.message": "Envoyer un message",
722
"opt.close": "Fermer",
723
"info.title": "Infos",
724
"info.lives": "Vies",
725
"info.ap": "Points d'action",
726
"info.range": "Portée",
727
"info.notes": "Vos notes privées",
728
"info.notesHint": "Vous seul pouvez voir ces notes. Elles sont enregistrées avec votre compte.",
729
"info.saveNotes": "Enregistrer les notes",
730
"info.saved": "Enregistré",
731
"give.title": "Donner des points d'action",
732
"give.howMany": "Combien ?",
733
"give.send": "Donner",
734
"give.youHave": "Vous en avez {n}.",
735
"chat.title": "Message à {name}",
736
"chat.placeholder": "Écrire un message privé…",
737
"chat.send": "Envoyer",
738
"chat.empty": "Pas encore de messages.",
739
"jury.title": "Jury",
740
"jury.hint": "Votez pour un joueur vivant. Celui qui obtient le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution. Vous pouvez changer votre vote jusque-là. Les autres joueurs ne voient pas votre vote.",
741
"jury.vote": "Voter",
742
"jury.votedFor": "Vous avez voté pour {name}",
743
"jury.change": "Changer de vote",
744
"timeline.play": "Lecture",
745
"timeline.pause": "Pause",
746
"timeline.live": "En direct",
747
"timeline.stepBack": "Reculer d’un pas",
748
"timeline.stepForward": "Avancer d’un pas",
749
"timeline.event.start": "La partie commence",
750
"timeline.event.move": "{name} se déplace",
751
"timeline.event.shoot": "{name} tire sur {target}",
752
"timeline.event.give": "{name} donne {n} point(s) d'action à {target}",
753
"timeline.event.upgrade": "{name} porte sa portée à {n}",
754
"timeline.event.surrender": "{name} abandonne",
755
"timeline.event.daily": "Jour {n} : distribution des points d'action",
756
"timeline.event.jury": "Le jury attribue un bonus à {name}",
757
"timeline.event.juryTie": "Le jury attribue un bonus à {names}",
758
"timeline.event.shrink": "L'arène rétrécit",
759
"timeline.event.win": "{name} gagne",
760
"timeline.event.death": "{name} est éliminé",
761
"timeline.event.deathShot": "{name} est abattu par {by}",
762
"timeline.event.deathShrink": "{name} est pris par l'arène qui rétrécit",
763
"timeline.event.deathCrushed": "{name} est écrasé : plus aucune case libre",
764
"timeline.event.draw": "La partie se termine par un match nul",
765
"auth.unavailable": "La connexion est temporairement indisponible.",
766
"auth.backToGame": "Retour à Allianties",
767
"auth.failed": "Échec de la connexion.",
768
"auth.retry": "Réessayer",
769
"auth.back": "Retour",
770
"lang.choose": "Choisir la langue",
771
"lang.current": "Langue : {name}",
772
"error.login": "Connectez-vous pour continuer.",
773
"error.csrf": "Votre session a expiré. Actualisez la page et réessayez.",
774
"error.not_host": "Seul l'hôte peut faire cela.",
775
"error.min_players": "Il faut au moins deux joueurs pour commencer.",
776
"error.not_in_game": "Vous n'êtes pas dans cette partie.",
777
"error.dead": "Vous êtes éliminé de cette partie.",
778
"error.no_ap": "Vous n'avez plus de points d'action.",
779
"error.occupied": "Cette case est occupée.",
780
"error.impassable": "Cette case est infranchissable.",
781
"error.out_of_range": "Ce joueur est hors de portée.",
782
"error.invalid_move": "Ce coup n'est pas autorisé.",
783
"error.game_started": "Cette partie a déjà commencé.",
784
"error.game_finished": "Cette partie est terminée.",
785
"error.lobby_full": "Ce salon est complet.",
786
"error.unknown_code": "Aucun salon trouvé avec ce code.",
787
"error.cannot_vote": "Vous ne pouvez pas voter maintenant.",
788
"error.bad_vote": "Vous ne pouvez voter que pour un joueur vivant.",
789
"error.bad_give": "Vous ne pouvez pas donner autant de points d'action.",
790
"error.unknown_action": "Action inconnue.",
791
"error.ceasefire": "Vous ne pouvez pas attaquer pendant le cessez-le-feu.",
792
"error.generic": "Un problème est survenu. Veuillez réessayer.",
793
"error.serverStatus": "Le serveur a renvoyé {status}."
794
},
795
"ja": {
796
"app.name": "Allianties",
797
"menu.tagline": "忍耐、同盟、そして時機を逃さない一撃のゲーム。",
798
"menu.login": "ログイン",
799
"menu.logout": "ログアウト",
800
"menu.loggedInAs": "ログイン中",
801
"menu.localTest": "ローカルテスト:",
802
"menu.create": "新しいロビー",
803
"menu.join": "参加",
804
"menu.codePlaceholder": "コード",
805
"menu.myGames": "あなたのゲーム",
806
"menu.noGames": "まだゲームがありません。ロビーを作って他の人を招待しましょう。",
807
"menu.authUnconfiguredHtml": "このサーバーではまだログインが設定されていません。コールバック <code>/allianties/callback.php</code> を auth.timfalken.com に登録し、クライアントシークレットを設定する必要があります。",
808
"menu.guestHint": "ログインすると、ロビーの作成、招待、長く続くゲームの開始ができます。",
809
"menu.open": "開く",
810
"menu.continue": "続ける",
811
"menu.statusLobby": "ロビー",
812
"menu.statusRunning": "プレイ中",
813
"menu.statusFinished": "終了",
814
"menu.youWon": "勝利",
815
"menu.draw": "引き分け",
816
"menu.winnerIs": "勝者:{name}",
817
"menu.needLogin": "プレイするには、まずログインしてください。",
818
"menu.players": "プレイヤー",
819
"lobby.title": "ロビー",
820
"lobby.invite": "招待",
821
"lobby.copy": "リンクをコピー",
822
"lobby.copied": "コピーしました",
823
"lobby.shareHint": "このコードまたはリンクを共有してください。プレイヤーはログインして参加します。",
824
"lobby.players": "プレイヤー",
825
"lobby.start": "ゲームを開始",
826
"lobby.leave": "ロビーを退出",
827
"lobby.host": "ホスト",
828
"lobby.you": "あなた",
829
"lobby.minPlayers": "開始するには少なくとも2人必要です。",
830
"lobby.needTwo": "あと少なくとも1人を待っています…",
831
"lobby.rules": "ルール",
832
"lobby.jury": "陪審",
833
"lobby.juryHint": "脱落したプレイヤーは毎日、生存中のプレイヤー1人に投票します。最多得票のプレイヤーは、次の毎日配布で行動力を1つ余分に受け取ります。同票の場合は、同票の全員がボーナスを受け取ります。投票は秘密で、配布まで変更できます。",
834
"lobby.shrink": "縮小する戦場",
835
"lobby.shrinkHint": "設定した日数ごとに、毎日の配布のときに外周が通行不能になります。その上にいるプレイヤーはライフを1失い、内側へ押し出されます。",
836
"lobby.shrinkDays": "縮小の間隔(日)",
837
"lobby.shrinkDaysHint": "最初の縮小はこの回数の深夜のあと、その後同じ日数ごとに繰り返し、戦場が最小サイズになるまで続きます。",
838
"lobby.ceasefire": "強制停戦時間",
839
"lobby.ceasefireHint": "この時間帯(Europe/Amsterdam)は誰も撃てません。移動、行動力の譲渡、射程の強化は可能です。時間帯は深夜をまたげます。",
840
"lobby.ceasefireAdd": "時間帯を追加",
841
"lobby.ceasefireRemove": "削除",
842
"lobby.ceasefireStart": "開始",
843
"lobby.ceasefireEnd": "終了",
844
"lobby.ceasefireEmpty": "まだ時間帯がありません。追加するか、時計の上で扇形をドラッグしてください。",
845
"lobby.ceasefireClock": "24時間時計。ハンドルをドラッグするか扇形を描きます。赤は停戦、金は攻撃可能。時刻は Europe/Amsterdam です。",
846
"lobby.apLoot": "倒した相手のアクションポイントを奪う",
847
"lobby.apLootHint": "射撃で相手を倒すと、残っていたアクションポイントを得ます。投降や縮小する戦場では移りません。既定はオフです。",
848
"lobby.apTime": "毎日のアクションポイント配布時刻",
849
"lobby.apTimeHint": "Europe/Amsterdam。アクションポイント、陪審のボーナス、戦場の縮小は毎日この時刻に行われます。既定は 00:00 です。",
850
"lobby.visibility": "公開範囲",
851
"lobby.visibilityHint": "誰が何を見られるか。自分のライフ、アクションポイント、射程は常に見えます。移動は常に公開です。サーバーが閲覧者ごとにそれ以外を隠し、隠された出来事はタイムラインに一切表示されません。",
852
"lobby.visShots": "射撃",
853
"lobby.visShotsPublic": "公開",
854
"lobby.visShotsElimPublic": "公開されるのは倒した射撃のみ",
855
"lobby.visShotsKnownTarget": "対象にのみ分かる",
856
"lobby.visShotsElimKnownTarget": "対象に分かるのは倒した射撃のみ",
857
"lobby.visGifts": "譲渡",
858
"lobby.visGiftsPublic": "公開",
859
"lobby.visGiftsKnownRecipient": "受け手にのみ分かる",
860
"lobby.visGiftsAnonymous": "匿名 — 受け手はポイントを得るが、誰からかは自分で推論する",
861
"lobby.visAp": "アクションポイント合計",
862
"lobby.visApPublic": "公開",
863
"lobby.visApHidden": "非公開",
864
"lobby.visRange": "射程",
865
"lobby.visRangePublic": "公開",
866
"lobby.visRangeInRange": "射程内のプレイヤーに分かる",
867
"lobby.visRangeHidden": "非公開",
868
"lobby.visLives": "ライフ",
869
"lobby.visLivesPublic": "公開",
870
"lobby.visLivesHidden": "非公開",
871
"info.hidden": "非公開",
872
"lobby.waiting": "ホストがゲームを開始するのを待っています。",
873
"lobby.back": "戻る",
874
"lobby.code": "コード",
875
"lobby.playerCount.one": "{n}人のプレイヤー",
876
"lobby.playerCount.other": "{n}人のプレイヤー",
877
"lobby.playerCount.few": "{n}人のプレイヤー",
878
"lobby.playerCount.many": "{n}人のプレイヤー",
879
"game.day": "{n}日目",
880
"game.nextAp": "次の行動力",
881
"game.lives": "ライフ",
882
"game.ap": "行動力",
883
"game.range": "射程",
884
"game.you": "あなた",
885
"game.dead": "脱落",
886
"game.surrendered": "降伏",
887
"game.winner": "{name}の勝利!",
888
"game.youWin": "あなたの勝利!",
889
"game.draw": "引き分けでゲーム終了です。",
890
"game.shrinkIn": "戦場は{n}日後に縮小します",
891
"game.shrinkInDays.one": "戦場は{n}日後に縮小します",
892
"game.shrinkInDays.other": "戦場は{n}日後に縮小します",
893
"game.shrinkInDays.few": "戦場は{n}日後に縮小します",
894
"game.shrinkInDays.many": "戦場は{n}日後に縮小します",
895
"game.shrinkTomorrow": "戦場は明日縮小します",
896
"game.shrinkToday": "戦場は次の配布時に縮小します",
897
"game.upgrade": "射程を伸ばす",
898
"game.settings": "設定",
899
"game.surrender": "降伏する",
900
"game.surrenderConfirm": "降伏しますか?このゲームから脱落します。取り消すことはできません。",
901
"game.surrenderConfirmBtn": "はい、降伏する",
902
"game.surrenderCancel": "キャンセル",
903
"game.back": "メニューに戻る",
904
"game.spectating": "あなたは脱落しました。観戦、メッセージ送信、陪審がオンなら投票はできます。",
905
"game.ceasefireLeft": "停戦の残り時間",
906
"game.ceasefireUntil": "停戦までの時間",
907
"game.ceasefireActive": "停戦中",
908
"game.attackDisabled": "攻撃",
909
"game.attackDisabledReason": "停戦時間中は攻撃できません。",
910
"game.selectSelf": "自分の戦車が選ばれています。ハイライトされたマスをタップして移動するか、射程を伸ばしてください。",
911
"game.impassable": "通行不能",
912
"game.willShrink": "次に縮小する輪",
913
"opt.info": "情報",
914
"opt.attack": "攻撃",
915
"opt.give": "行動力を渡す",
916
"opt.message": "メッセージを送る",
917
"opt.close": "閉じる",
918
"info.title": "情報",
919
"info.lives": "ライフ",
920
"info.ap": "行動力",
921
"info.range": "射程",
922
"info.notes": "非公開のメモ",
923
"info.notesHint": "このメモはあなただけが見られます。アカウントに保存されます。",
924
"info.saveNotes": "メモを保存",
925
"info.saved": "保存しました",
926
"give.title": "行動力を渡す",
927
"give.howMany": "いくつ?",
928
"give.send": "渡す",
929
"give.youHave": "あなたは{n}持っています。",
930
"chat.title": "{name}へのメッセージ",
931
"chat.placeholder": "非公開メッセージを書く…",
932
"chat.send": "送信",
933
"chat.empty": "まだメッセージはありません。",
934
"jury.title": "陪審",
935
"jury.hint": "生存中のプレイヤー1人に投票します。最多得票者は次の配布で行動力を1つ余分に得ます。それまで投票は変更できます。他のプレイヤーに投票は見えません。",
936
"jury.vote": "投票する",
937
"jury.votedFor": "{name}に投票しました",
938
"jury.change": "投票を変更",
939
"timeline.play": "再生",
940
"timeline.pause": "一時停止",
941
"timeline.live": "ライブ",
942
"timeline.stepBack": "一つ戻る",
943
"timeline.stepForward": "一つ進む",
944
"timeline.event.start": "ゲーム開始",
945
"timeline.event.move": "{name}が移動",
946
"timeline.event.shoot": "{name}が{target}を撃つ",
947
"timeline.event.give": "{name}が{target}に行動力を{n}渡す",
948
"timeline.event.upgrade": "{name}が射程を{n}に伸ばす",
949
"timeline.event.surrender": "{name}が降伏",
950
"timeline.event.daily": "{n}日目:行動力の配布",
951
"timeline.event.jury": "陪審が{name}にボーナスを与える",
952
"timeline.event.juryTie": "陪審が{names}にボーナスを与える",
953
"timeline.event.shrink": "戦場が縮小する",
954
"timeline.event.win": "{name}の勝利",
955
"timeline.event.death": "{name}が脱落",
956
"timeline.event.deathShot": "{name}が{by}に撃たれて脱落",
957
"timeline.event.deathShrink": "{name}が縮小する戦場に巻き込まれた",
958
"timeline.event.deathCrushed": "{name}は押しつぶされた:空きマスがない",
959
"timeline.event.draw": "引き分けで終了",
960
"auth.unavailable": "ログインは一時的に利用できません。",
961
"auth.backToGame": "Alliantiesに戻る",
962
"auth.failed": "ログインに失敗しました。",
963
"auth.retry": "再試行",
964
"auth.back": "戻る",
965
"lang.choose": "言語を選択",
966
"lang.current": "言語:{name}",
967
"error.login": "続けるにはログインしてください。",
968
"error.csrf": "セッションの期限が切れました。ページを更新してもう一度お試しください。",
969
"error.not_host": "ホストだけがそれを行えます。",
970
"error.min_players": "開始するには少なくとも2人必要です。",
971
"error.not_in_game": "このゲームには参加していません。",
972
"error.dead": "このゲームから脱落しています。",
973
"error.no_ap": "行動力が残っていません。",
974
"error.occupied": "そのマスは占有されています。",
975
"error.impassable": "そのマスは通行不能です。",
976
"error.out_of_range": "そのプレイヤーは射程外です。",
977
"error.invalid_move": "その行動はできません。",
978
"error.game_started": "このゲームはすでに始まっています。",
979
"error.game_finished": "このゲームは終了しています。",
980
"error.lobby_full": "このロビーは満員です。",
981
"error.unknown_code": "そのコードのロビーは見つかりません。",
982
"error.cannot_vote": "今は投票できません。",
983
"error.bad_vote": "生存中のプレイヤーにしか投票できません。",
984
"error.bad_give": "そんなに多くの行動力は渡せません。",
985
"error.unknown_action": "不明な行動です。",
986
"error.ceasefire": "停戦時間中は攻撃できません。",
987
"error.generic": "問題が発生しました。もう一度お試しください。",
988
"error.serverStatus": "サーバーは{status}を返しました。"
989
},
990
"zh": {
991
"app.name": "Allianties",
992
"menu.tagline": "一场关于耐心、同盟与精准开火的游戏。",
993
"menu.login": "登录",
994
"menu.logout": "退出登录",
995
"menu.loggedInAs": "已登录为",
996
"menu.localTest": "本地测试:",
997
"menu.create": "新建大厅",
998
"menu.join": "加入",
999
"menu.codePlaceholder": "代码",
1000
"menu.myGames": "你的对局",
1001
"menu.noGames": "你还没有任何对局。新建一个大厅并邀请其他人吧。",
1002
"menu.authUnconfiguredHtml": "此服务器尚未设置登录。需要在 auth.timfalken.com 上注册回调 <code>/allianties/callback.php</code>,并配置客户端密钥。",
1003
"menu.guestHint": "登录后可以创建大厅、邀请玩家并开始一局长时间进行的游戏。",
1004
"menu.open": "打开",
1005
"menu.continue": "继续",
1006
"menu.statusLobby": "大厅",
1007
"menu.statusRunning": "进行中",
1008
"menu.statusFinished": "已结束",
1009
"menu.youWon": "你赢了",
1010
"menu.draw": "平局",
1011
"menu.winnerIs": "胜者:{name}",
1012
"menu.needLogin": "请先登录再游戏。",
1013
"menu.players": "玩家",
1014
"lobby.title": "大厅",
1015
"lobby.invite": "邀请",
1016
"lobby.copy": "复制链接",
1017
"lobby.copied": "已复制",
1018
"lobby.shareHint": "分享此代码或链接。玩家登录后即可加入。",
1019
"lobby.players": "玩家",
1020
"lobby.start": "开始游戏",
1021
"lobby.leave": "离开大厅",
1022
"lobby.host": "房主",
1023
"lobby.you": "你",
1024
"lobby.minPlayers": "至少需要两名玩家才能开始。",
1025
"lobby.needTwo": "正在等待至少再来一名玩家…",
1026
"lobby.rules": "规则",
1027
"lobby.jury": "陪审团",
1028
"lobby.juryHint": "被淘汰的玩家每天为一名仍存活的玩家投票。得票最多的玩家在下一次每日发放时额外获得 1 点行动点。若并列,所有并列者都获得奖励。投票对他人保密,并可在发放前更改。",
1029
"lobby.shrink": "缩小的战场",
1030
"lobby.shrinkHint": "每隔设定的天数,在每日发放时外圈会变为不可通行。站在上面的玩家失去 1 点生命并被推向内侧。",
1031
"lobby.shrinkDays": "两次缩小间隔天数",
1032
"lobby.shrinkDaysHint": "第一次缩小发生在这么多个午夜之后,之后每隔同样天数再缩小,直到战场达到最小尺寸。",
1033
"lobby.ceasefire": "强制停火时段",
1034
"lobby.ceasefireHint": "在这些时段(Europe/Amsterdam)任何人不得射击。移动、给予行动点和提升射程仍然允许。时段可以跨越午夜。",
1035
"lobby.ceasefireAdd": "添加时段",
1036
"lobby.ceasefireRemove": "删除",
1037
"lobby.ceasefireStart": "从",
1038
"lobby.ceasefireEnd": "至",
1039
"lobby.ceasefireEmpty": "还没有时段。请添加一个,或在时钟上拖出一段扇形。",
1040
"lobby.ceasefireClock": "24 小时时钟。拖动手柄或画出扇形;红色为停火,金色为可开火。时间为 Europe/Amsterdam。",
1041
"lobby.apLoot": "击杀时夺取行动点",
1042
"lobby.apLootHint": "用射击淘汰玩家时,你会获得其剩余行动点。投降和缩小场地不会转移点数。默认关闭。",
1043
"lobby.apTime": "每日行动点发放时间",
1044
"lobby.apTimeHint": "Europe/Amsterdam。行动点、陪审团奖励和场地缩小每天都在此时发生。默认 00:00。",
1045
"lobby.visibility": "可见性",
1046
"lobby.visibilityHint": "谁能看到什么。你始终能看到自己的生命、行动点和射程。移动始终公开。服务器会按观看者隐藏其余信息;被隐藏的事件完全不会出现在时间轴上。",
1047
"lobby.visShots": "射击",
1048
"lobby.visShotsPublic": "公开",
1049
"lobby.visShotsElimPublic": "仅公开淘汰性射击",
1050
"lobby.visShotsKnownTarget": "仅目标知晓",
1051
"lobby.visShotsElimKnownTarget": "仅淘汰性射击为目标所知",
1052
"lobby.visGifts": "赠予",
1053
"lobby.visGiftsPublic": "公开",
1054
"lobby.visGiftsKnownRecipient": "仅接收者知晓",
1055
"lobby.visGiftsAnonymous": "匿名——接收者获得点数,但须自行推断来自谁",
1056
"lobby.visAp": "行动点总数",
1057
"lobby.visApPublic": "公开",
1058
"lobby.visApHidden": "隐藏",
1059
"lobby.visRange": "射程",
1060
"lobby.visRangePublic": "公开",
1061
"lobby.visRangeInRange": "射程内的玩家可知",
1062
"lobby.visRangeHidden": "隐藏",
1063
"lobby.visLives": "生命",
1064
"lobby.visLivesPublic": "公开",
1065
"lobby.visLivesHidden": "隐藏",
1066
"info.hidden": "隐藏",
1067
"lobby.waiting": "等待房主开始游戏。",
1068
"lobby.back": "返回",
1069
"lobby.code": "代码",
1070
"lobby.playerCount.one": "{n} 名玩家",
1071
"lobby.playerCount.other": "{n} 名玩家",
1072
"lobby.playerCount.few": "{n} 名玩家",
1073
"lobby.playerCount.many": "{n} 名玩家",
1074
"game.day": "第 {n} 天",
1075
"game.nextAp": "下次行动点",
1076
"game.lives": "生命",
1077
"game.ap": "行动点",
1078
"game.range": "射程",
1079
"game.you": "你",
1080
"game.dead": "已淘汰",
1081
"game.surrendered": "已投降",
1082
"game.winner": "{name} 获胜!",
1083
"game.youWin": "你赢了!",
1084
"game.draw": "本局以平局结束。",
1085
"game.shrinkIn": "战场将在 {n} 天后缩小",
1086
"game.shrinkInDays.one": "战场将在 {n} 天后缩小",
1087
"game.shrinkInDays.other": "战场将在 {n} 天后缩小",
1088
"game.shrinkInDays.few": "战场将在 {n} 天后缩小",
1089
"game.shrinkInDays.many": "战场将在 {n} 天后缩小",
1090
"game.shrinkTomorrow": "战场将在明天缩小",
1091
"game.shrinkToday": "战场将在下次发放时缩小",
1092
"game.upgrade": "提升射程",
1093
"game.settings": "设置",
1094
"game.surrender": "投降",
1095
"game.surrenderConfirm": "确定投降?你将退出本局,且无法撤销。",
1096
"game.surrenderConfirmBtn": "是的,投降",
1097
"game.surrenderCancel": "取消",
1098
"game.back": "返回菜单",
1099
"game.spectating": "你已被淘汰。你仍可观战、发送消息,并在陪审团开启时投票。",
1100
"game.ceasefireLeft": "停火剩余时间",
1101
"game.ceasefireUntil": "距离停火",
1102
"game.ceasefireActive": "停火中",
1103
"game.attackDisabled": "攻击",
1104
"game.attackDisabledReason": "停火时段内不得攻击。",
1105
"game.selectSelf": "已选中你的坦克。点按高亮格子移动,或提升射程。",
1106
"game.impassable": "不可通行",
1107
"game.willShrink": "下一圈将缩小",
1108
"opt.info": "信息",
1109
"opt.attack": "攻击",
1110
"opt.give": "给予行动点",
1111
"opt.message": "发送消息",
1112
"opt.close": "关闭",
1113
"info.title": "信息",
1114
"info.lives": "生命",
1115
"info.ap": "行动点",
1116
"info.range": "射程",
1117
"info.notes": "你的私人备注",
1118
"info.notesHint": "只有你能看到这些备注。它们保存在你的账户中。",
1119
"info.saveNotes": "保存备注",
1120
"info.saved": "已保存",
1121
"give.title": "给予行动点",
1122
"give.howMany": "给多少?",
1123
"give.send": "给予",
1124
"give.youHave": "你有 {n} 点。",
1125
"chat.title": "给 {name} 的消息",
1126
"chat.placeholder": "写一条私人消息…",
1127
"chat.send": "发送",
1128
"chat.empty": "还没有消息。",
1129
"jury.title": "陪审团",
1130
"jury.hint": "为一名仍存活的玩家投票。得票最多者在下次发放时额外获得 1 点行动点。在此之前可以改票。其他玩家看不到你的投票。",
1131
"jury.vote": "投票",
1132
"jury.votedFor": "你把票投给了 {name}",
1133
"jury.change": "改票",
1134
"timeline.play": "播放",
1135
"timeline.pause": "暂停",
1136
"timeline.live": "实时",
1137
"timeline.stepBack": "后退一步",
1138
"timeline.stepForward": "前进一步",
1139
"timeline.event.start": "游戏开始",
1140
"timeline.event.move": "{name} 移动了",
1141
"timeline.event.shoot": "{name} 向 {target} 射击",
1142
"timeline.event.give": "{name} 将 {n} 点行动点给了 {target}",
1143
"timeline.event.upgrade": "{name} 将射程提升到 {n}",
1144
"timeline.event.surrender": "{name} 投降了",
1145
"timeline.event.daily": "第 {n} 天:发放行动点",
1146
"timeline.event.jury": "陪审团将奖励发给 {name}",
1147
"timeline.event.juryTie": "陪审团将奖励发给 {names}",
1148
"timeline.event.shrink": "战场缩小了",
1149
"timeline.event.win": "{name} 获胜",
1150
"timeline.event.death": "{name} 被淘汰",
1151
"timeline.event.deathShot": "{name} 被 {by} 击倒",
1152
"timeline.event.deathShrink": "{name} 被缩小的战场波及",
1153
"timeline.event.deathCrushed": "{name} 被挤出:没有空余格子",
1154
"timeline.event.draw": "本局以平局结束",
1155
"auth.unavailable": "登录暂时不可用。",
1156
"auth.backToGame": "返回 Allianties",
1157
"auth.failed": "登录失败。",
1158
"auth.retry": "重试",
1159
"auth.back": "返回",
1160
"lang.choose": "选择语言",
1161
"lang.current": "语言:{name}",
1162
"error.login": "请登录后再继续。",
1163
"error.csrf": "会话已过期。请刷新页面后再试。",
1164
"error.not_host": "只有房主可以这样做。",
1165
"error.min_players": "至少需要两名玩家才能开始。",
1166
"error.not_in_game": "你不在这局游戏中。",
1167
"error.dead": "你已从本局淘汰。",
1168
"error.no_ap": "你没有剩余的行动点。",
1169
"error.occupied": "该格子已被占用。",
1170
"error.impassable": "该格子不可通行。",
1171
"error.out_of_range": "该玩家超出射程。",
1172
"error.invalid_move": "不允许这样行动。",
1173
"error.game_started": "这局游戏已经开始。",
1174
"error.game_finished": "这局游戏已经结束。",
1175
"error.lobby_full": "此大厅已满。",
1176
"error.unknown_code": "找不到该代码对应的大厅。",
1177
"error.cannot_vote": "你现在不能投票。",
1178
"error.bad_vote": "只能为仍存活的玩家投票。",
1179
"error.bad_give": "不能给予那么多行动点。",
1180
"error.unknown_action": "未知操作。",
1181
"error.ceasefire": "停火时段内不能攻击。",
1182
"error.generic": "出了点问题,请再试一次。",
1183
"error.serverStatus": "服务器返回了 {status}。"
1184
},
1185
"ko": {
1186
"app.name": "Allianties",
1187
"menu.tagline": "인내와 동맹, 그리고 때를 놓치지 않는 사격의 게임.",
1188
"menu.login": "로그인",
1189
"menu.logout": "로그아웃",
1190
"menu.loggedInAs": "로그인됨",
1191
"menu.localTest": "로컬 테스트:",
1192
"menu.create": "새 로비",
1193
"menu.join": "참가",
1194
"menu.codePlaceholder": "코드",
1195
"menu.myGames": "내 게임",
1196
"menu.noGames": "아직 게임이 없습니다. 로비를 만들고 다른 사람을 초대하세요.",
1197
"menu.authUnconfiguredHtml": "이 서버에는 아직 로그인이 설정되지 않았습니다. 콜백 <code>/allianties/callback.php</code>를 auth.timfalken.com에 등록하고 클라이언트 비밀키를 설정해야 합니다.",
1198
"menu.guestHint": "로그인하면 로비를 만들고, 플레이어를 초대하고, 오래 이어지는 게임을 시작할 수 있습니다.",
1199
"menu.open": "열기",
1200
"menu.continue": "계속",
1201
"menu.statusLobby": "로비",
1202
"menu.statusRunning": "진행 중",
1203
"menu.statusFinished": "종료",
1204
"menu.youWon": "승리",
1205
"menu.draw": "무승부",
1206
"menu.winnerIs": "승자: {name}",
1207
"menu.needLogin": "플레이하려면 먼저 로그인하세요.",
1208
"menu.players": "플레이어",
1209
"lobby.title": "로비",
1210
"lobby.invite": "초대",
1211
"lobby.copy": "링크 복사",
1212
"lobby.copied": "복사됨",
1213
"lobby.shareHint": "이 코드나 링크를 공유하세요. 플레이어는 로그인한 뒤 참가합니다.",
1214
"lobby.players": "플레이어",
1215
"lobby.start": "게임 시작",
1216
"lobby.leave": "로비 나가기",
1217
"lobby.host": "호스트",
1218
"lobby.you": "나",
1219
"lobby.minPlayers": "시작하려면 플레이어가 최소 두 명 필요합니다.",
1220
"lobby.needTwo": "플레이어를 최소 한 명 더 기다리는 중…",
1221
"lobby.rules": "규칙",
1222
"lobby.jury": "배심",
1223
"lobby.juryHint": "탈락한 플레이어는 매일 생존 중인 플레이어 한 명에게 투표합니다. 가장 많은 표를 받은 플레이어는 다음 일일 지급 때 행동력을 하나 더 받습니다. 동점이면 동점인 전원에게 보너스가 갑니다. 표는 비밀이며 지급 전까지 바꿀 수 있습니다.",
1224
"lobby.shrink": "줄어드는 전장",
1225
"lobby.shrinkHint": "설정한 일수가 지나면 일일 지급 때 바깥 고리가 통과 불가가 됩니다. 그 위에 있는 플레이어는 목숨을 하나 잃고 안쪽으로 밀립니다.",
1226
"lobby.shrinkDays": "축소 간격(일)",
1227
"lobby.shrinkDaysHint": "첫 축소는 그 횟수만큼의 자정이 지난 뒤, 이후 같은 일수마다 반복되며 전장이 최소 크기에 이를 때까지 계속됩니다.",
1228
"lobby.ceasefire": "강제 휴전 시간",
1229
"lobby.ceasefireHint": "이 시간대(Europe/Amsterdam)에는 아무도 발사할 수 없습니다. 이동, 행동력 전달, 사거리 강화는 가능합니다. 구간은 자정을 넘길 수 있습니다.",
1230
"lobby.ceasefireAdd": "구간 추가",
1231
"lobby.ceasefireRemove": "삭제",
1232
"lobby.ceasefireStart": "시작",
1233
"lobby.ceasefireEnd": "종료",
1234
"lobby.ceasefireEmpty": "아직 구간이 없습니다. 하나를 추가하거나 시계에서 부채꼴을 드래그하세요.",
1235
"lobby.ceasefireClock": "24시간 시계. 핸들을 드래그하거나 부채꼴을 그리세요. 빨강은 휴전, 금색은 사격 가능. 시각은 Europe/Amsterdam입니다.",
1236
"lobby.apLoot": "처치 시 행동력 탈취",
1237
"lobby.apLootHint": "사격으로 플레이어를 처치하면 남은 행동력을 받습니다. 항복과 축소되는 전장에서는 이전되지 않습니다. 기본값은 꺼짐입니다.",
1238
"lobby.apTime": "매일 행동력 지급 시각",
1239
"lobby.apTimeHint": "Europe/Amsterdam. 행동력, 배심 보너스, 전장 축소가 매일 이 시각에 일어납니다. 기본값은 00:00입니다.",
1240
"lobby.visibility": "공개 범위",
1241
"lobby.visibilityHint": "누가 무엇을 볼 수 있는지. 자신의 생명, 행동력, 사거리는 항상 보입니다. 이동은 항상 공개됩니다. 서버가 보는 사람마다 나머지를 숨기며, 숨겨진 사건은 타임라인에 전혀 나타나지 않습니다.",
1242
"lobby.visShots": "사격",
1243
"lobby.visShotsPublic": "공개",
1244
"lobby.visShotsElimPublic": "처치하는 사격만 공개",
1245
"lobby.visShotsKnownTarget": "대상만 알 수 있음",
1246
"lobby.visShotsElimKnownTarget": "대상은 처치하는 사격만 알 수 있음",
1247
"lobby.visGifts": "선물",
1248
"lobby.visGiftsPublic": "공개",
1249
"lobby.visGiftsKnownRecipient": "받는 사람만 알 수 있음",
1250
"lobby.visGiftsAnonymous": "익명 — 받는 사람은 점수를 얻지만 누가 줬는지는 스스로 추론해야 함",
1251
"lobby.visAp": "행동력 합계",
1252
"lobby.visApPublic": "공개",
1253
"lobby.visApHidden": "숨김",
1254
"lobby.visRange": "사거리",
1255
"lobby.visRangePublic": "공개",
1256
"lobby.visRangeInRange": "사거리 안의 플레이어에게 알려짐",
1257
"lobby.visRangeHidden": "숨김",
1258
"lobby.visLives": "생명",
1259
"lobby.visLivesPublic": "공개",
1260
"lobby.visLivesHidden": "숨김",
1261
"info.hidden": "숨김",
1262
"lobby.waiting": "호스트가 게임을 시작하기를 기다리는 중.",
1263
"lobby.back": "뒤로",
1264
"lobby.code": "코드",
1265
"lobby.playerCount.one": "플레이어 {n}명",
1266
"lobby.playerCount.other": "플레이어 {n}명",
1267
"lobby.playerCount.few": "플레이어 {n}명",
1268
"lobby.playerCount.many": "플레이어 {n}명",
1269
"game.day": "{n}일차",
1270
"game.nextAp": "다음 행동력",
1271
"game.lives": "목숨",
1272
"game.ap": "행동력",
1273
"game.range": "사거리",
1274
"game.you": "나",
1275
"game.dead": "탈락",
1276
"game.surrendered": "항복함",
1277
"game.winner": "{name} 승리!",
1278
"game.youWin": "당신이 이겼습니다!",
1279
"game.draw": "게임이 무승부로 끝났습니다.",
1280
"game.shrinkIn": "전장이 {n}일 후 줄어듭니다",
1281
"game.shrinkInDays.one": "전장이 {n}일 후 줄어듭니다",
1282
"game.shrinkInDays.other": "전장이 {n}일 후 줄어듭니다",
1283
"game.shrinkInDays.few": "전장이 {n}일 후 줄어듭니다",
1284
"game.shrinkInDays.many": "전장이 {n}일 후 줄어듭니다",
1285
"game.shrinkTomorrow": "전장이 내일 줄어듭니다",
1286
"game.shrinkToday": "전장이 다음 지급 때 줄어듭니다",
1287
"game.upgrade": "사거리 강화",
1288
"game.settings": "설정",
1289
"game.surrender": "항복",
1290
"game.surrenderConfirm": "항복할까요? 이 게임에서 탈락하며 되돌릴 수 없습니다.",
1291
"game.surrenderConfirmBtn": "네, 항복합니다",
1292
"game.surrenderCancel": "취소",
1293
"game.back": "메뉴로 돌아가기",
1294
"game.spectating": "탈락했습니다. 관전, 메시지 보내기, 배심이 켜져 있다면 투표는 계속할 수 있습니다.",
1295
"game.ceasefireLeft": "휴전 남은 시간",
1296
"game.ceasefireUntil": "휴전까지",
1297
"game.ceasefireActive": "휴전 중",
1298
"game.attackDisabled": "공격",
1299
"game.attackDisabledReason": "휴전 시간에는 공격할 수 없습니다.",
1300
"game.selectSelf": "내 전차가 선택되었습니다. 강조된 칸을 눌러 이동하거나 사거리를 강화하세요.",
1301
"game.impassable": "통과 불가",
1302
"game.willShrink": "다음에 줄어들 고리",
1303
"opt.info": "정보",
1304
"opt.attack": "공격",
1305
"opt.give": "행동력 주기",
1306
"opt.message": "메시지 보내기",
1307
"opt.close": "닫기",
1308
"info.title": "정보",
1309
"info.lives": "목숨",
1310
"info.ap": "행동력",
1311
"info.range": "사거리",
1312
"info.notes": "나만 보는 메모",
1313
"info.notesHint": "이 메모는 당신만 볼 수 있습니다. 계정에 저장됩니다.",
1314
"info.saveNotes": "메모 저장",
1315
"info.saved": "저장됨",
1316
"give.title": "행동력 주기",
1317
"give.howMany": "몇 개?",
1318
"give.send": "주기",
1319
"give.youHave": "{n}개를 가지고 있습니다.",
1320
"chat.title": "{name}에게 메시지",
1321
"chat.placeholder": "비공개 메시지를 작성하세요…",
1322
"chat.send": "보내기",
1323
"chat.empty": "아직 메시지가 없습니다.",
1324
"jury.title": "배심",
1325
"jury.hint": "생존 중인 플레이어 한 명에게 투표하세요. 가장 많은 표를 받은 사람은 다음 지급 때 행동력을 하나 더 받습니다. 그 전까지 표를 바꿀 수 있습니다. 다른 플레이어는 당신의 표를 볼 수 없습니다.",
1326
"jury.vote": "투표",
1327
"jury.votedFor": "{name}에게 투표했습니다",
1328
"jury.change": "투표 변경",
1329
"timeline.play": "재생",
1330
"timeline.pause": "일시정지",
1331
"timeline.live": "실시간",
1332
"timeline.stepBack": "한 단계 뒤로",
1333
"timeline.stepForward": "한 단계 앞으로",
1334
"timeline.event.start": "게임이 시작됩니다",
1335
"timeline.event.move": "{name}이(가) 이동합니다",
1336
"timeline.event.shoot": "{name}이(가) {target}을(를) 공격합니다",
1337
"timeline.event.give": "{name}이(가) {target}에게 행동력 {n}개를 줍니다",
1338
"timeline.event.upgrade": "{name}이(가) 사거리를 {n}(으)로 올립니다",
1339
"timeline.event.surrender": "{name}이(가) 항복합니다",
1340
"timeline.event.daily": "{n}일차: 행동력 지급",
1341
"timeline.event.jury": "배심이 {name}에게 보너스를 줍니다",
1342
"timeline.event.juryTie": "배심이 {names}에게 보너스를 줍니다",
1343
"timeline.event.shrink": "전장이 줄어듭니다",
1344
"timeline.event.win": "{name} 승리",
1345
"timeline.event.death": "{name} 탈락",
1346
"timeline.event.deathShot": "{name}이(가) {by}에게 피격되어 탈락",
1347
"timeline.event.deathShrink": "{name}이(가) 줄어드는 전장에 걸렸습니다",
1348
"timeline.event.deathCrushed": "{name}이(가) 깔렸습니다: 빈 칸이 없습니다",
1349
"timeline.event.draw": "게임이 무승부로 끝납니다",
1350
"auth.unavailable": "로그인을 잠시 사용할 수 없습니다.",
1351
"auth.backToGame": "Allianties로 돌아가기",
1352
"auth.failed": "로그인에 실패했습니다.",
1353
"auth.retry": "다시 시도",
1354
"auth.back": "뒤로",
1355
"lang.choose": "언어 선택",
1356
"lang.current": "언어: {name}",
1357
"error.login": "계속하려면 로그인하세요.",
1358
"error.csrf": "세션이 만료되었습니다. 페이지를 새로 고친 뒤 다시 시도하세요.",
1359
"error.not_host": "호스트만 할 수 있습니다.",
1360
"error.min_players": "시작하려면 플레이어가 최소 두 명 필요합니다.",
1361
"error.not_in_game": "이 게임에 들어가 있지 않습니다.",
1362
"error.dead": "이 게임에서 탈락했습니다.",
1363
"error.no_ap": "남은 행동력이 없습니다.",
1364
"error.occupied": "그 칸은 이미 차지되어 있습니다.",
1365
"error.impassable": "그 칸은 통과할 수 없습니다.",
1366
"error.out_of_range": "그 플레이어는 사거리 밖입니다.",
1367
"error.invalid_move": "그 행동은 허용되지 않습니다.",
1368
"error.game_started": "이 게임은 이미 시작되었습니다.",
1369
"error.game_finished": "이 게임은 이미 끝났습니다.",
1370
"error.lobby_full": "이 로비는 가득 찼습니다.",
1371
"error.unknown_code": "그 코드의 로비를 찾을 수 없습니다.",
1372
"error.cannot_vote": "지금은 투표할 수 없습니다.",
1373
"error.bad_vote": "생존 중인 플레이어에게만 투표할 수 있습니다.",
1374
"error.bad_give": "그만큼의 행동력은 줄 수 없습니다.",
1375
"error.unknown_action": "알 수 없는 행동입니다.",
1376
"error.ceasefire": "휴전 시간에는 공격할 수 없습니다.",
1377
"error.generic": "문제가 발생했습니다. 다시 시도해 주세요.",
1378
"error.serverStatus": "서버가 {status}을(를) 반환했습니다."
1379
},
1380
"pl": {
1381
"app.name": "Allianties",
1382
"menu.tagline": "Gra cierpliwości, sojuszy i dobrze wycelowanych strzałów.",
1383
"menu.login": "Zaloguj się",
1384
"menu.logout": "Wyloguj się",
1385
"menu.loggedInAs": "Zalogowano jako",
1386
"menu.localTest": "test lokalny:",
1387
"menu.create": "Nowe lobby",
1388
"menu.join": "Dołącz",
1389
"menu.codePlaceholder": "Kod",
1390
"menu.myGames": "Twoje gry",
1391
"menu.noGames": "Nie masz jeszcze żadnych gier. Załóż lobby i zaproś innych.",
1392
"menu.authUnconfiguredHtml": "Logowanie nie jest jeszcze skonfigurowane na tym serwerze. Callback <code>/allianties/callback.php</code> musi zostać zarejestrowany w auth.timfalken.com, a sekret klienta musi zostać ustawiony.",
1393
"menu.guestHint": "Zaloguj się, aby utworzyć lobby, zaprosić graczy i rozpocząć trwałą rozgrywkę.",
1394
"menu.open": "Otwórz",
1395
"menu.continue": "Kontynuuj",
1396
"menu.statusLobby": "Lobby",
1397
"menu.statusRunning": "W toku",
1398
"menu.statusFinished": "Zakończona",
1399
"menu.youWon": "Wygrana",
1400
"menu.draw": "Remis",
1401
"menu.winnerIs": "Zwycięzca: {name}",
1402
"menu.needLogin": "Najpierw zaloguj się, aby zagrać.",
1403
"menu.players": "Gracze",
1404
"lobby.title": "Lobby",
1405
"lobby.invite": "Zaproś",
1406
"lobby.copy": "Kopiuj link",
1407
"lobby.copied": "Skopiowano",
1408
"lobby.shareHint": "Udostępnij ten kod lub link. Gracze logują się i dołączają.",
1409
"lobby.players": "Gracze",
1410
"lobby.start": "Rozpocznij grę",
1411
"lobby.leave": "Opuść lobby",
1412
"lobby.host": "Gospodarz",
1413
"lobby.you": "ty",
1414
"lobby.minPlayers": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",
1415
"lobby.needTwo": "Oczekiwanie na co najmniej jednego gracza…",
1416
"lobby.rules": "Zasady",
1417
"lobby.jury": "Jury",
1418
"lobby.juryHint": "Eliminowani gracze codziennie głosują na żywego gracza. Osoba z największą liczbą głosów otrzymuje dodatkowy punkt akcji przy kolejnym codziennym rozdaniu. Przy remisie bonus dostaje każdy z ex aequo. Głosy są tajne i można je zmieniać do tego momentu.",
1419
"lobby.shrink": "Kurcząca się arena",
1420
"lobby.shrinkHint": "Po ustalonej liczbie dni zewnętrzny pierścień staje się nieprzekraczalny przy codziennym rozdaniu. Gracze, którzy na nim stoją, tracą jedno życie i są spychani do środka.",
1421
"lobby.shrinkDays": "Dni między skurczeniami",
1422
"lobby.shrinkDaysHint": "Pierwsze skurczenie po tylu północach, potem ponownie co tyle samo dni, aż arena osiągnie minimalny rozmiar.",
1423
"lobby.ceasefire": "Wymuszone godziny zawieszenia broni",
1424
"lobby.ceasefireHint": "W tych godzinach (Europe/Amsterdam) nikt nie może strzelać. Ruch, przekazywanie punktów akcji i zwiększanie zasięgu pozostają dozwolone. Zakresy mogą przekraczać północ.",
1425
"lobby.ceasefireAdd": "Dodaj okres",
1426
"lobby.ceasefireRemove": "Usuń",
1427
"lobby.ceasefireStart": "Od",
1428
"lobby.ceasefireEnd": "Do",
1429
"lobby.ceasefireEmpty": "Brak okresów. Dodaj jeden albo narysuj wycinek na zegarze.",
1430
"lobby.ceasefireClock": "Zegar 24-godzinny. Przeciągaj uchwyty lub maluj wycinek; czerwień to zawieszenie broni, złoto to dowolność strzału. Czas: Europe/Amsterdam.",
1431
"lobby.apLoot": "Przejmowanie punktów akcji przy eliminacji",
1432
"lobby.apLootHint": "Gdy wyeliminujesz gracza strzałem, otrzymujesz jego pozostałe punkty akcji. Poddanie się i kurczenie areny nie przekazują punktów. Domyślnie wyłączone.",
1433
"lobby.apTime": "Codzienne punkty akcji o",
1434
"lobby.apTimeHint": "Europe/Amsterdam. Punkty akcji, nagrody jury i kurczenie areny odbywają się codziennie o tej godzinie. Domyślnie 00:00.",
1435
"lobby.visibility": "Widoczność",
1436
"lobby.visibilityHint": "Kto co widzi. Zawsze widzisz własne życia, punkty akcji i zasięg. Ruchy są zawsze publiczne. Serwer ukrywa resztę przed każdym widzem; ukryte zdarzenia w ogóle nie pojawiają się na osi czasu.",
1437
"lobby.visShots": "Strzały",
1438
"lobby.visShotsPublic": "Publiczne",
1439
"lobby.visShotsElimPublic": "Publiczne są tylko strzały eliminujące",
1440
"lobby.visShotsKnownTarget": "Znane tylko celowi",
1441
"lobby.visShotsElimKnownTarget": "Cel zna tylko strzał eliminujący",
1442
"lobby.visGifts": "Dary",
1443
"lobby.visGiftsPublic": "Publiczne",
1444
"lobby.visGiftsKnownRecipient": "Znane tylko odbiorcy",
1445
"lobby.visGiftsAnonymous": "Anonimowo — odbiorca dostaje punkty, ale musi sam wywnioskować, od kogo",
1446
"lobby.visAp": "Sumy punktów akcji",
1447
"lobby.visApPublic": "Publiczne",
1448
"lobby.visApHidden": "Ukryte",
1449
"lobby.visRange": "Zasięg",
1450
"lobby.visRangePublic": "Publiczne",
1451
"lobby.visRangeInRange": "Znane graczom w zasięgu",
1452
"lobby.visRangeHidden": "Ukryte",
1453
"lobby.visLives": "Życia",
1454
"lobby.visLivesPublic": "Publiczne",
1455
"lobby.visLivesHidden": "Ukryte",
1456
"info.hidden": "Ukryte",
1457
"lobby.waiting": "Czekamy, aż gospodarz rozpocznie grę.",
1458
"lobby.back": "Wstecz",
1459
"lobby.code": "Kod",
1460
"lobby.playerCount.one": "{n} gracz",
1461
"lobby.playerCount.other": "{n} graczy",
1462
"lobby.playerCount.few": "{n} graczy",
1463
"lobby.playerCount.many": "{n} graczy",
1464
"game.day": "Dzień {n}",
1465
"game.nextAp": "Następne punkty akcji",
1466
"game.lives": "Życia",
1467
"game.ap": "Punkty akcji",
1468
"game.range": "Zasięg",
1469
"game.you": "Ty",
1470
"game.dead": "Eliminacja",
1471
"game.surrendered": "Poddał się",
1472
"game.winner": "{name} wygrywa!",
1473
"game.youWin": "Wygrywasz!",
1474
"game.draw": "Gra kończy się remisem.",
1475
"game.shrinkIn": "Arena skurczy się za {n} dni",
1476
"game.shrinkInDays.one": "Arena skurczy się za {n} dzień",
1477
"game.shrinkInDays.other": "Arena skurczy się za {n} dni",
1478
"game.shrinkInDays.few": "Arena skurczy się za {n} dni",
1479
"game.shrinkInDays.many": "Arena skurczy się za {n} dni",
1480
"game.shrinkTomorrow": "Arena skurczy się jutro",
1481
"game.shrinkToday": "Arena skurczy się przy następnym rozdaniu",
1482
"game.upgrade": "Zwiększ zasięg",
1483
"game.settings": "Ustawienia",
1484
"game.surrender": "Poddaj się",
1485
"game.surrenderConfirm": "Poddać się? Odpadniesz z tej gry. Tej czynności nie można cofnąć.",
1486
"game.surrenderConfirmBtn": "Tak, poddaję się",
1487
"game.surrenderCancel": "Anuluj",
1488
"game.back": "Powrót do menu",
1489
"game.spectating": "Odpadłeś. Nadal możesz oglądać, wysyłać wiadomości i — jeśli jury jest włączone — głosować.",
1490
"game.ceasefireLeft": "Pozostały czas zawieszenia broni",
1491
"game.ceasefireUntil": "Czas do zawieszenia broni",
1492
"game.ceasefireActive": "Zawieszenie broni",
1493
"game.attackDisabled": "Atak",
1494
"game.attackDisabledReason": "Atak jest niedozwolony w godzinach zawieszenia broni.",
1495
"game.selectSelf": "Twój czołg jest zaznaczony. Dotknij podświetlonego pola, aby się ruszyć, albo zwiększ zasięg.",
1496
"game.impassable": "Nieprzekraczalne",
1497
"game.willShrink": "Ten pierścień skurczy się jako następny",
1498
"opt.info": "Informacje",
1499
"opt.attack": "Atakuj",
1500
"opt.give": "Przekaż punkty akcji",
1501
"opt.message": "Wyślij wiadomość",
1502
"opt.close": "Zamknij",
1503
"info.title": "Informacje",
1504
"info.lives": "Życia",
1505
"info.ap": "Punkty akcji",
1506
"info.range": "Zasięg",
1507
"info.notes": "Twoje prywatne notatki",
1508
"info.notesHint": "Tylko ty widzisz te notatki. Są przechowywane przy twoim koncie.",
1509
"info.saveNotes": "Zapisz notatki",
1510
"info.saved": "Zapisano",
1511
"give.title": "Przekaż punkty akcji",
1512
"give.howMany": "Ile?",
1513
"give.send": "Przekaż",
1514
"give.youHave": "Masz {n}.",
1515
"chat.title": "Wiadomość do {name}",
1516
"chat.placeholder": "Napisz prywatną wiadomość…",
1517
"chat.send": "Wyślij",
1518
"chat.empty": "Nie ma jeszcze wiadomości.",
1519
"jury.title": "Jury",
1520
"jury.hint": "Zagłosuj na jednego żywego gracza. Osoba z największą liczbą głosów otrzyma dodatkowy punkt akcji przy następnym rozdaniu. Do tego czasu możesz zmienić głos. Inni gracze go nie widzą.",
1521
"jury.vote": "Głosuj",
1522
"jury.votedFor": "Zagłosowałeś na {name}",
1523
"jury.change": "Zmień głos",
1524
"timeline.play": "Odtwórz",
1525
"timeline.pause": "Pauza",
1526
"timeline.live": "Na żywo",
1527
"timeline.stepBack": "Krok wstecz",
1528
"timeline.stepForward": "Krok naprzód",
1529
"timeline.event.start": "Gra się zaczyna",
1530
"timeline.event.move": "{name} się przemieszcza",
1531
"timeline.event.shoot": "{name} strzela do {target}",
1532
"timeline.event.give": "{name} przekazuje {n} pkt. akcji dla {target}",
1533
"timeline.event.upgrade": "{name} zwiększa zasięg do {n}",
1534
"timeline.event.surrender": "{name} się poddaje",
1535
"timeline.event.daily": "Dzień {n}: rozdanie punktów akcji",
1536
"timeline.event.jury": "Jury przyznaje bonus dla {name}",
1537
"timeline.event.juryTie": "Jury przyznaje bonus dla {names}",
1538
"timeline.event.shrink": "Arena się kurczy",
1539
"timeline.event.win": "{name} wygrywa",
1540
"timeline.event.death": "{name} odpada",
1541
"timeline.event.deathShot": "{name} zostaje zestrzelony przez {by}",
1542
"timeline.event.deathShrink": "{name} zostaje złapany przez kurczącą się arenę",
1543
"timeline.event.deathCrushed": "{name} zostaje zmiażdżony: nie ma wolnego pola",
1544
"timeline.event.draw": "Gra kończy się remisem",
1545
"auth.unavailable": "Logowanie jest chwilowo niedostępne.",
1546
"auth.backToGame": "Powrót do Allianties",
1547
"auth.failed": "Logowanie nie powiodło się.",
1548
"auth.retry": "Spróbuj ponownie",
1549
"auth.back": "Wstecz",
1550
"lang.choose": "Wybierz język",
1551
"lang.current": "Język: {name}",
1552
"error.login": "Zaloguj się, aby kontynuować.",
1553
"error.csrf": "Twoja sesja wygasła. Odśwież stronę i spróbuj ponownie.",
1554
"error.not_host": "Tylko gospodarz może to zrobić.",
1555
"error.min_players": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",
1556
"error.not_in_game": "Nie jesteś w tej grze.",
1557
"error.dead": "Odpadłeś z tej gry.",
1558
"error.no_ap": "Nie masz już punktów akcji.",
1559
"error.occupied": "To pole jest zajęte.",
1560
"error.impassable": "To pole jest nieprzekraczalne.",
1561
"error.out_of_range": "Ten gracz jest poza zasięgiem.",
1562
"error.invalid_move": "Ten ruch jest niedozwolony.",
1563
"error.game_started": "Ta gra już się rozpoczęła.",
1564
"error.game_finished": "Ta gra się zakończyła.",
1565
"error.lobby_full": "To lobby jest pełne.",
1566
"error.unknown_code": "Nie znaleziono lobby o takim kodzie.",
1567
"error.cannot_vote": "Teraz nie możesz głosować.",
1568
"error.bad_vote": "Możesz głosować tylko na żywego gracza.",
1569
"error.bad_give": "Nie możesz przekazać tylu punktów akcji.",
1570
"error.unknown_action": "Nieznana akcja.",
1571
"error.ceasefire": "Nie możesz atakować w godzinach zawieszenia broni.",
1572
"error.generic": "Coś poszło nie tak. Spróbuj ponownie.",
1573
"error.serverStatus": "Serwer zwrócił {status}."
1574
},
1575
"ru": {
1576
"app.name": "Allianties",
1577
"menu.tagline": "Игра в терпение, союзы и хорошо рассчитанные выстрелы.",
1578
"menu.login": "Войти",
1579
"menu.logout": "Выйти",
1580
"menu.loggedInAs": "Вы вошли как",
1581
"menu.localTest": "локальный тест:",
1582
"menu.create": "Новое лобби",
1583
"menu.join": "Присоединиться",
1584
"menu.codePlaceholder": "Код",
1585
"menu.myGames": "Ваши игры",
1586
"menu.noGames": "У вас пока нет игр. Создайте лобби и пригласите других.",
1587
"menu.authUnconfiguredHtml": "Вход на этом сервере ещё не настроен. Callback <code>/allianties/callback.php</code> нужно зарегистрировать на auth.timfalken.com, а секрет клиента — задать.",
1588
"menu.guestHint": "Войдите, чтобы создать лобби, пригласить игроков и начать долгую партию.",
1589
"menu.open": "Открыть",
1590
"menu.continue": "Продолжить",
1591
"menu.statusLobby": "Лобби",
1592
"menu.statusRunning": "Идёт игра",
1593
"menu.statusFinished": "Завершена",
1594
"menu.youWon": "Вы победили",
1595
"menu.draw": "Ничья",
1596
"menu.winnerIs": "Победитель: {name}",
1597
"menu.needLogin": "Сначала войдите, чтобы играть.",
1598
"menu.players": "Игроки",
1599
"lobby.title": "Лобби",
1600
"lobby.invite": "Пригласить",
1601
"lobby.copy": "Копировать ссылку",
1602
"lobby.copied": "Скопировано",
1603
"lobby.shareHint": "Поделитесь этим кодом или ссылкой. Игроки входят в аккаунт и присоединяются.",
1604
"lobby.players": "Игроки",
1605
"lobby.start": "Начать игру",
1606
"lobby.leave": "Покинуть лобби",
1607
"lobby.host": "Хозяин",
1608
"lobby.you": "вы",
1609
"lobby.minPlayers": "Для начала нужно как минимум два игрока.",
1610
"lobby.needTwo": "Ждём ещё хотя бы одного игрока…",
1611
"lobby.rules": "Правила",
1612
"lobby.jury": "Жюри",
1613
"lobby.juryHint": "Выбывшие игроки каждый день голосуют за живого игрока. Набравший больше всех голосов получает дополнительное очко действия при следующем ежедневном начислении. При ничьей бонус получают все, кто набрал одинаково максимум. Голоса тайные и их можно менять до начисления.",
1614
"lobby.shrink": "Сжимающаяся арена",
1615
"lobby.shrinkHint": "Через заданное число дней внешнее кольцо становится непроходимым в момент ежедневного начисления. Игроки, стоящие на нём, теряют одну жизнь и сдвигаются внутрь.",
1616
"lobby.shrinkDays": "Дней между сжатиями",
1617
"lobby.shrinkDaysHint": "Первое сжатие после стольких полуночей, затем снова через столько же дней, пока арена не достигнет минимального размера.",
1618
"lobby.ceasefire": "Принудительное перемирие",
1619
"lobby.ceasefireHint": "В эти часы (Europe/Amsterdam) стрелять нельзя. Ходить, передавать очки действия и увеличивать дальность по-прежнему можно. Интервалы могут переходить через полночь.",
1620
"lobby.ceasefireAdd": "Добавить период",
1621
"lobby.ceasefireRemove": "Удалить",
1622
"lobby.ceasefireStart": "С",
1623
"lobby.ceasefireEnd": "До",
1624
"lobby.ceasefireEmpty": "Периодов пока нет. Добавьте один или нарисуйте сектор на часах.",
1625
"lobby.ceasefireClock": "24-часовые часы. Перетаскивайте ручки или рисуйте сектор; красный — перемирие, золотой — огонь разрешён. Время: Europe/Amsterdam.",
1626
"lobby.apLoot": "Забирать очки действий при убийстве",
1627
"lobby.apLootHint": "Если вы устраняете игрока выстрелом, вы получаете его оставшиеся очки действий. Сдача и сужение арены очки не передают. По умолчанию выключено.",
1628
"lobby.apTime": "Ежедневные очки действий в",
1629
"lobby.apTimeHint": "Europe/Amsterdam. Очки действий, бонусы жюри и сужение арены происходят каждый день в это время. По умолчанию 00:00.",
1630
"lobby.visibility": "Видимость",
1631
"lobby.visibilityHint": "Кто что видит. Вы всегда видите свои жизни, очки действий и дальность. Перемещение всегда открыто. Сервер скрывает всё остальное для каждого зрителя; скрытые события вообще не появляются на шкале времени.",
1632
"lobby.visShots": "Выстрелы",
1633
"lobby.visShotsPublic": "Открыто",
1634
"lobby.visShotsElimPublic": "Открыты только устраняющие выстрелы",
1635
"lobby.visShotsKnownTarget": "Известно только цели",
1636
"lobby.visShotsElimKnownTarget": "Цели известен только устраняющий выстрел",
1637
"lobby.visGifts": "Подарки",
1638
"lobby.visGiftsPublic": "Открыто",
1639
"lobby.visGiftsKnownRecipient": "Известно только получателю",
1640
"lobby.visGiftsAnonymous": "Анонимно — получатель получает очки, но должен сам догадаться, от кого",
1641
"lobby.visAp": "Запасы очков действий",
1642
"lobby.visApPublic": "Открыто",
1643
"lobby.visApHidden": "Скрыто",
1644
"lobby.visRange": "Дальность",
1645
"lobby.visRangePublic": "Открыто",
1646
"lobby.visRangeInRange": "Известно игрокам в пределах дальности",
1647
"lobby.visRangeHidden": "Скрыто",
1648
"lobby.visLives": "Жизни",
1649
"lobby.visLivesPublic": "Открыто",
1650
"lobby.visLivesHidden": "Скрыто",
1651
"info.hidden": "Скрыто",
1652
"lobby.waiting": "Ждём, пока хозяин начнёт игру.",
1653
"lobby.back": "Назад",
1654
"lobby.code": "Код",
1655
"lobby.playerCount.one": "{n} игрок",
1656
"lobby.playerCount.other": "{n} игроков",
1657
"lobby.playerCount.few": "{n} игрока",
1658
"lobby.playerCount.many": "{n} игроков",
1659
"game.day": "День {n}",
1660
"game.nextAp": "Следующие очки действия",
1661
"game.lives": "Жизни",
1662
"game.ap": "Очки действия",
1663
"game.range": "Дальность",
1664
"game.you": "Вы",
1665
"game.dead": "Выбыл",
1666
"game.surrendered": "Сдался",
1667
"game.winner": "{name} побеждает!",
1668
"game.youWin": "Вы победили!",
1669
"game.draw": "Игра заканчивается вничью.",
1670
"game.shrinkIn": "Арена сожмётся через {n} дн.",
1671
"game.shrinkInDays.one": "Арена сожмётся через {n} день",
1672
"game.shrinkInDays.other": "Арена сожмётся через {n} дней",
1673
"game.shrinkInDays.few": "Арена сожмётся через {n} дня",
1674
"game.shrinkInDays.many": "Арена сожмётся через {n} дней",
1675
"game.shrinkTomorrow": "Арена сожмётся завтра",
1676
"game.shrinkToday": "Арена сожмётся при следующем начислении",
1677
"game.upgrade": "Увеличить дальность",
1678
"game.settings": "Настройки",
1679
"game.surrender": "Сдаться",
1680
"game.surrenderConfirm": "Сдаться? Вы выбудете из этой игры. Это нельзя отменить.",
1681
"game.surrenderConfirmBtn": "Да, сдаться",
1682
"game.surrenderCancel": "Отмена",
1683
"game.back": "Вернуться в меню",
1684
"game.spectating": "Вы выбыли. Можно смотреть, писать сообщения и, если жюри включено, голосовать.",
1685
"game.ceasefireLeft": "До конца перемирия",
1686
"game.ceasefireUntil": "До начала перемирия",
1687
"game.ceasefireActive": "Перемирие",
1688
"game.attackDisabled": "Атака",
1689
"game.attackDisabledReason": "Во время перемирия атаковать нельзя.",
1690
"game.selectSelf": "Ваш танк выбран. Нажмите подсвеченную клетку, чтобы пойти, или увеличьте дальность.",
1691
"game.impassable": "Непроходимо",
1692
"game.willShrink": "Это кольцо сожмётся следующим",
1693
"opt.info": "Сведения",
1694
"opt.attack": "Атаковать",
1695
"opt.give": "Отдать очки действия",
1696
"opt.message": "Отправить сообщение",
1697
"opt.close": "Закрыть",
1698
"info.title": "Сведения",
1699
"info.lives": "Жизни",
1700
"info.ap": "Очки действия",
1701
"info.range": "Дальность",
1702
"info.notes": "Ваши личные заметки",
1703
"info.notesHint": "Эти заметки видите только вы. Они хранятся в вашем аккаунте.",
1704
"info.saveNotes": "Сохранить заметки",
1705
"info.saved": "Сохранено",
1706
"give.title": "Отдать очки действия",
1707
"give.howMany": "Сколько?",
1708
"give.send": "Отдать",
1709
"give.youHave": "У вас {n}.",
1710
"chat.title": "Сообщение для {name}",
1711
"chat.placeholder": "Напишите личное сообщение…",
1712
"chat.send": "Отправить",
1713
"chat.empty": "Сообщений пока нет.",
1714
"jury.title": "Жюри",
1715
"jury.hint": "Голосуйте за одного живого игрока. Набравший больше всех голосов получит дополнительное очко действия при следующем начислении. Голос можно менять до этого момента. Другие игроки его не видят.",
1716
"jury.vote": "Голосовать",
1717
"jury.votedFor": "Вы проголосовали за {name}",
1718
"jury.change": "Изменить голос",
1719
"timeline.play": "Воспроизвести",
1720
"timeline.pause": "Пауза",
1721
"timeline.live": "Сейчас",
1722
"timeline.stepBack": "На шаг назад",
1723
"timeline.stepForward": "На шаг вперёд",
1724
"timeline.event.start": "Игра начинается",
1725
"timeline.event.move": "{name} перемещается",
1726
"timeline.event.shoot": "{name} стреляет в {target}",
1727
"timeline.event.give": "{name} отдаёт {n} очк. действия игроку {target}",
1728
"timeline.event.upgrade": "{name} увеличивает дальность до {n}",
1729
"timeline.event.surrender": "{name} сдаётся",
1730
"timeline.event.daily": "День {n}: начисление очков действия",
1731
"timeline.event.jury": "Жюри присуждает бонус игроку {name}",
1732
"timeline.event.juryTie": "Жюри присуждает бонус игрокам {names}",
1733
"timeline.event.shrink": "Арена сжимается",
1734
"timeline.event.win": "{name} побеждает",
1735
"timeline.event.death": "{name} выбывает",
1736
"timeline.event.deathShot": "{name} подбит игроком {by}",
1737
"timeline.event.deathShrink": "{name} задевает сжимающаяся арена",
1738
"timeline.event.deathCrushed": "{name} раздавлен: свободных клеток не осталось",
1739
"timeline.event.draw": "Игра заканчивается вничью",
1740
"auth.unavailable": "Вход временно недоступен.",
1741
"auth.backToGame": "Назад в Allianties",
1742
"auth.failed": "Не удалось войти.",
1743
"auth.retry": "Попробовать снова",
1744
"auth.back": "Назад",
1745
"lang.choose": "Выберите язык",
1746
"lang.current": "Язык: {name}",
1747
"error.login": "Войдите, чтобы продолжить.",
1748
"error.csrf": "Сессия истекла. Обновите страницу и попробуйте снова.",
1749
"error.not_host": "Это может сделать только хозяин.",
1750
"error.min_players": "Для начала нужно как минимум два игрока.",
1751
"error.not_in_game": "Вас нет в этой игре.",
1752
"error.dead": "Вы выбыли из этой игры.",
1753
"error.no_ap": "У вас не осталось очков действия.",
1754
"error.occupied": "Эта клетка занята.",
1755
"error.impassable": "Эта клетка непроходима.",
1756
"error.out_of_range": "Этот игрок вне досягаемости.",
1757
"error.invalid_move": "Этот ход недопустим.",
1758
"error.game_started": "Эта игра уже началась.",
1759
"error.game_finished": "Эта игра уже закончена.",
1760
"error.lobby_full": "Это лобби заполнено.",
1761
"error.unknown_code": "Лобби с таким кодом не найдено.",
1762
"error.cannot_vote": "Сейчас вы не можете голосовать.",
1763
"error.bad_vote": "Голосовать можно только за живого игрока.",
1764
"error.bad_give": "Столько очков действия отдать нельзя.",
1765
"error.unknown_action": "Неизвестное действие.",
1766
"error.ceasefire": "Во время перемирия атаковать нельзя.",
1767
"error.generic": "Что-то пошло не так. Попробуйте ещё раз.",
1768
"error.serverStatus": "Сервер вернул {status}."
1769
},
1770
"es": {
1771
"app.name": "Allianties",
1772
"menu.tagline": "Un juego de paciencia, alianzas y disparos bien calculados.",
1773
"menu.login": "Iniciar sesión",
1774
"menu.logout": "Cerrar sesión",
1775
"menu.loggedInAs": "Sesión iniciada como",
1776
"menu.localTest": "prueba local:",
1777
"menu.create": "Nueva sala",
1778
"menu.join": "Unirse",
1779
"menu.codePlaceholder": "Código",
1780
"menu.myGames": "Tus partidas",
1781
"menu.noGames": "Aún no tienes partidas. Crea una sala e invita a otros.",
1782
"menu.authUnconfiguredHtml": "El inicio de sesión aún no está configurado en este servidor. Hay que registrar la callback <code>/allianties/callback.php</code> en auth.timfalken.com y configurar el secreto del cliente.",
1783
"menu.guestHint": "Inicia sesión para crear una sala, invitar jugadores y empezar una partida duradera.",
1784
"menu.open": "Abrir",
1785
"menu.continue": "Continuar",
1786
"menu.statusLobby": "Sala",
1787
"menu.statusRunning": "En juego",
1788
"menu.statusFinished": "Terminada",
1789
"menu.youWon": "Has ganado",
1790
"menu.draw": "Empate",
1791
"menu.winnerIs": "Ganador: {name}",
1792
"menu.needLogin": "Inicia sesión primero para jugar.",
1793
"menu.players": "Jugadores",
1794
"lobby.title": "Sala",
1795
"lobby.invite": "Invitar",
1796
"lobby.copy": "Copiar enlace",
1797
"lobby.copied": "Copiado",
1798
"lobby.shareHint": "Comparte este código o enlace. Los jugadores inician sesión y se unen.",
1799
"lobby.players": "Jugadores",
1800
"lobby.start": "Empezar partida",
1801
"lobby.leave": "Salir de la sala",
1802
"lobby.host": "Anfitrión",
1803
"lobby.you": "tú",
1804
"lobby.minPlayers": "Hacen falta al menos dos jugadores para empezar.",
1805
"lobby.needTwo": "Esperando al menos a un jugador más…",
1806
"lobby.rules": "Reglas",
1807
"lobby.jury": "Jurado",
1808
"lobby.juryHint": "Los jugadores eliminados votan cada día por un jugador vivo. Quien recibe más votos obtiene un punto de acción extra en el siguiente reparto diario. En caso de empate, cada jugador empatado recibe la bonificación. Los votos son secretos y se pueden cambiar hasta entonces.",
1809
"lobby.shrink": "Arena que se encoge",
1810
"lobby.shrinkHint": "Tras un número configurable de días, el anillo exterior se vuelve intransitable en el reparto diario. Los jugadores que estén encima pierden una vida y son empujados hacia dentro.",
1811
"lobby.shrinkDays": "Días entre encogimientos",
1812
"lobby.shrinkDaysHint": "El primer encogimiento tras tantas medianoches, y luego cada vez que pasen otros tantos días, hasta el tamaño mínimo de la arena.",
1813
"lobby.ceasefire": "Horas de alto el fuego forzoso",
1814
"lobby.ceasefireHint": "Durante estas horas (Europe/Amsterdam) nadie puede disparar. Moverse, dar puntos de acción y mejorar el alcance siguen permitidos. Los periodos pueden cruzar la medianoche.",
1815
"lobby.ceasefireAdd": "Añadir periodo",
1816
"lobby.ceasefireRemove": "Quitar",
1817
"lobby.ceasefireStart": "Desde",
1818
"lobby.ceasefireEnd": "Hasta",
1819
"lobby.ceasefireEmpty": "Aún no hay periodos. Añade uno o arrastra un sector en el reloj.",
1820
"lobby.ceasefireClock": "Reloj de 24 horas. Arrastra los tiradores o pinta un sector; el rojo es alto el fuego, el oro es fuego libre. Horarios en Europe/Amsterdam.",
1821
"lobby.apLoot": "Saquear puntos de acción al eliminar",
1822
"lobby.apLootHint": "Si eliminas a un jugador de un disparo, recibes sus puntos de acción restantes. Rendirse y la arena que se encoge no transfieren puntos. Desactivado por defecto.",
1823
"lobby.apTime": "Puntos de acción diarios a las",
1824
"lobby.apTimeHint": "Europe/Amsterdam. Los puntos de acción, los bonus del jurado y la reducción de la arena ocurren cada día a esta hora. Por defecto 00:00.",
1825
"lobby.visibility": "Visibilidad",
1826
"lobby.visibilityHint": "Quién puede ver qué. Siempre ves tus propias vidas, puntos de acción y alcance. El movimiento es siempre público. El servidor oculta el resto a cada espectador; los sucesos ocultos no aparecen en absoluto en la línea de tiempo.",
1827
"lobby.visShots": "Disparos",
1828
"lobby.visShotsPublic": "Público",
1829
"lobby.visShotsElimPublic": "Solo son públicos los disparos que eliminan",
1830
"lobby.visShotsKnownTarget": "Solo lo sabe el objetivo",
1831
"lobby.visShotsElimKnownTarget": "El objetivo solo conoce los disparos que lo eliminan",
1832
"lobby.visGifts": "Regalos",
1833
"lobby.visGiftsPublic": "Público",
1834
"lobby.visGiftsKnownRecipient": "Solo lo sabe el destinatario",
1835
"lobby.visGiftsAnonymous": "Anónimo: el destinatario recibe los puntos pero debe deducir de quién",
1836
"lobby.visAp": "Totales de puntos de acción",
1837
"lobby.visApPublic": "Público",
1838
"lobby.visApHidden": "Oculto",
1839
"lobby.visRange": "Alcance",
1840
"lobby.visRangePublic": "Público",
1841
"lobby.visRangeInRange": "Lo saben los jugadores que están a alcance",
1842
"lobby.visRangeHidden": "Oculto",
1843
"lobby.visLives": "Vidas",
1844
"lobby.visLivesPublic": "Público",
1845
"lobby.visLivesHidden": "Oculto",
1846
"info.hidden": "Oculto",
1847
"lobby.waiting": "Esperando a que el anfitrión empiece la partida.",
1848
"lobby.back": "Volver",
1849
"lobby.code": "Código",
1850
"lobby.playerCount.one": "{n} jugador",
1851
"lobby.playerCount.other": "{n} jugadores",
1852
"lobby.playerCount.few": "{n} jugadores",
1853
"lobby.playerCount.many": "{n} jugadores",
1854
"game.day": "Día {n}",
1855
"game.nextAp": "Próximos puntos de acción",
1856
"game.lives": "Vidas",
1857
"game.ap": "Puntos de acción",
1858
"game.range": "Alcance",
1859
"game.you": "Tú",
1860
"game.dead": "Eliminado",
1861
"game.surrendered": "Se rindió",
1862
"game.winner": "¡{name} gana!",
1863
"game.youWin": "¡Has ganado!",
1864
"game.draw": "La partida termina en empate.",
1865
"game.shrinkIn": "La arena se encoge en {n} días",
1866
"game.shrinkInDays.one": "La arena se encoge en {n} día",
1867
"game.shrinkInDays.other": "La arena se encoge en {n} días",
1868
"game.shrinkInDays.few": "La arena se encoge en {n} días",
1869
"game.shrinkInDays.many": "La arena se encoge en {n} días",
1870
"game.shrinkTomorrow": "La arena se encoge mañana",
1871
"game.shrinkToday": "La arena se encoge en el siguiente reparto",
1872
"game.upgrade": "Aumentar alcance",
1873
"game.settings": "Ajustes",
1874
"game.surrender": "Rendirse",
1875
"game.surrenderConfirm": "¿Rendirse? Quedarás fuera de esta partida. No se puede deshacer.",
1876
"game.surrenderConfirmBtn": "Sí, rendirme",
1877
"game.surrenderCancel": "Cancelar",
1878
"game.back": "Volver al menú",
1879
"game.spectating": "Estás eliminado. Aún puedes observar, enviar mensajes y, si el jurado está activo, votar.",
1880
"game.ceasefireLeft": "Tiempo restante de alto el fuego",
1881
"game.ceasefireUntil": "Tiempo hasta el alto el fuego",
1882
"game.ceasefireActive": "Alto el fuego",
1883
"game.attackDisabled": "Atacar",
1884
"game.attackDisabledReason": "No se puede atacar durante las horas de alto el fuego.",
1885
"game.selectSelf": "Tu tanque está seleccionado. Toca una casilla destacada para moverte, o aumenta tu alcance.",
1886
"game.impassable": "Intransitable",
1887
"game.willShrink": "Este anillo se encogerá a continuación",
1888
"opt.info": "Info",
1889
"opt.attack": "Atacar",
1890
"opt.give": "Dar puntos de acción",
1891
"opt.message": "Enviar mensaje",
1892
"opt.close": "Cerrar",
1893
"info.title": "Info",
1894
"info.lives": "Vidas",
1895
"info.ap": "Puntos de acción",
1896
"info.range": "Alcance",
1897
"info.notes": "Tus notas privadas",
1898
"info.notesHint": "Solo tú puedes ver estas notas. Se guardan con tu cuenta.",
1899
"info.saveNotes": "Guardar notas",
1900
"info.saved": "Guardado",
1901
"give.title": "Dar puntos de acción",
1902
"give.howMany": "¿Cuántos?",
1903
"give.send": "Dar",
1904
"give.youHave": "Tienes {n}.",
1905
"chat.title": "Mensaje a {name}",
1906
"chat.placeholder": "Escribe un mensaje privado…",
1907
"chat.send": "Enviar",
1908
"chat.empty": "Aún no hay mensajes.",
1909
"jury.title": "Jurado",
1910
"jury.hint": "Vota por un jugador vivo. Quien reciba más votos obtiene un punto de acción extra en el siguiente reparto. Puedes cambiar tu voto hasta entonces. Los demás no ven tu voto.",
1911
"jury.vote": "Votar",
1912
"jury.votedFor": "Has votado por {name}",
1913
"jury.change": "Cambiar voto",
1914
"timeline.play": "Reproducir",
1915
"timeline.pause": "Pausa",
1916
"timeline.live": "En directo",
1917
"timeline.stepBack": "Un paso atrás",
1918
"timeline.stepForward": "Un paso adelante",
1919
"timeline.event.start": "Empieza la partida",
1920
"timeline.event.move": "{name} se mueve",
1921
"timeline.event.shoot": "{name} dispara a {target}",
1922
"timeline.event.give": "{name} da {n} punto(s) de acción a {target}",
1923
"timeline.event.upgrade": "{name} aumenta el alcance a {n}",
1924
"timeline.event.surrender": "{name} se rinde",
1925
"timeline.event.daily": "Día {n}: se reparten los puntos de acción",
1926
"timeline.event.jury": "El jurado otorga una bonificación a {name}",
1927
"timeline.event.juryTie": "El jurado otorga una bonificación a {names}",
1928
"timeline.event.shrink": "La arena se encoge",
1929
"timeline.event.win": "{name} gana",
1930
"timeline.event.death": "{name} queda eliminado",
1931
"timeline.event.deathShot": "{by} dispara a {name} y lo elimina",
1932
"timeline.event.deathShrink": "{name} es alcanzado por la arena que se encoge",
1933
"timeline.event.deathCrushed": "{name} queda aplastado: no queda ninguna casilla libre",
1934
"timeline.event.draw": "La partida termina en empate",
1935
"auth.unavailable": "El inicio de sesión no está disponible temporalmente.",
1936
"auth.backToGame": "Volver a Allianties",
1937
"auth.failed": "Error al iniciar sesión.",
1938
"auth.retry": "Reintentar",
1939
"auth.back": "Volver",
1940
"lang.choose": "Elegir idioma",
1941
"lang.current": "Idioma: {name}",
1942
"error.login": "Inicia sesión para continuar.",
1943
"error.csrf": "Tu sesión ha caducado. Actualiza la página e inténtalo de nuevo.",
1944
"error.not_host": "Solo el anfitrión puede hacer eso.",
1945
"error.min_players": "Hacen falta al menos dos jugadores para empezar.",
1946
"error.not_in_game": "No estás en esta partida.",
1947
"error.dead": "Has quedado eliminado de esta partida.",
1948
"error.no_ap": "No te quedan puntos de acción.",
1949
"error.occupied": "Esa casilla está ocupada.",
1950
"error.impassable": "Esa casilla es intransitable.",
1951
"error.out_of_range": "Ese jugador está fuera de alcance.",
1952
"error.invalid_move": "Ese movimiento no está permitido.",
1953
"error.game_started": "Esta partida ya ha empezado.",
1954
"error.game_finished": "Esta partida ha terminado.",
1955
"error.lobby_full": "Esta sala está llena.",
1956
"error.unknown_code": "No se encontró ninguna sala con ese código.",
1957
"error.cannot_vote": "Ahora no puedes votar.",
1958
"error.bad_vote": "Solo puedes votar por un jugador vivo.",
1959
"error.bad_give": "No puedes dar tantos puntos de acción.",
1960
"error.unknown_action": "Acción desconocida.",
1961
"error.ceasefire": "No puedes atacar durante el alto el fuego.",
1962
"error.generic": "Algo salió mal. Inténtalo de nuevo.",
1963
"error.serverStatus": "El servidor devolvió {status}."
1964
}
1965
},
1966
"errors": {
1967
"login": "error.login",
1968
"csrf": "error.csrf",
1969
"not_host": "error.not_host",
1970
"min_players": "error.min_players",
1971
"not_in_game": "error.not_in_game",
1972
"dead": "error.dead",
1973
"no_ap": "error.no_ap",
1974
"occupied": "error.occupied",
1975
"impassable": "error.impassable",
1976
"out_of_range": "error.out_of_range",
1977
"invalid_move": "error.invalid_move",
1978
"game_started": "error.game_started",
1979
"game_finished": "error.game_finished",
1980
"lobby_full": "error.lobby_full",
1981
"unknown_code": "error.unknown_code",
1982
"cannot_vote": "error.cannot_vote",
1983
"bad_vote": "error.bad_vote",
1984
"bad_give": "error.bad_give",
1985
"unknown_action": "error.unknown_action",
1986
"ceasefire": "error.ceasefire",
1987
"generic": "error.generic"
1988
}
1989
}
@@ -0,0 +1,1989 @@1
{2
"localeIds": [3
"en",4
"nl",5
"de",6
"fr",7
"ja",8
"zh",9
"ko",10
"pl",11
"ru",12
"es"13
],14
"locales": {15
"en": {16
"app.name": "Allianties",17
"menu.tagline": "A game of patience, alliances and well-timed shots.",18
"menu.login": "Log in",19
"menu.logout": "Log out",20
"menu.loggedInAs": "Logged in as",21
"menu.localTest": "local test:",22
"menu.create": "New lobby",23
"menu.join": "Join",24
"menu.codePlaceholder": "Code",25
"menu.myGames": "Your games",26
"menu.noGames": "You have no games yet. Start a lobby and invite others.",27
"menu.authUnconfiguredHtml": "Sign-in is not set up on this server yet. The callback <code>/allianties/callback.php</code> must be registered at auth.timfalken.com, and the client secret must be configured.",28
"menu.guestHint": "Log in to create a lobby, invite players and start a lasting game.",29
"menu.open": "Open",30
"menu.continue": "Continue",31
"menu.statusLobby": "Lobby",32
"menu.statusRunning": "In play",33
"menu.statusFinished": "Finished",34
"menu.youWon": "You won",35
"menu.draw": "Draw",36
"menu.winnerIs": "Winner: {name}",37
"menu.needLogin": "Log in first to play.",38
"menu.players": "Players",39
"lobby.title": "Lobby",40
"lobby.invite": "Invite",41
"lobby.copy": "Copy link",42
"lobby.copied": "Copied",43
"lobby.shareHint": "Share this code or link. Players log in and join.",44
"lobby.players": "Players",45
"lobby.start": "Start game",46
"lobby.leave": "Leave lobby",47
"lobby.host": "Host",48
"lobby.you": "you",49
"lobby.minPlayers": "You need at least two players to start.",50
"lobby.needTwo": "Waiting for at least one more player…",51
"lobby.rules": "Rules",52
"lobby.jury": "Jury",53
"lobby.juryHint": "Dead players vote each day for a living player. The player with the most votes receives one extra action point at the next daily distribution. Ties: every tied player receives the bonus. Votes are secret and can be changed until then.",54
"lobby.shrink": "Shrinking arena",55
"lobby.shrinkHint": "After every set number of days, the outer ring becomes impassable at the daily distribution. Players standing on it lose one life and are pushed inward.",56
"lobby.shrinkDays": "Days between shrinks",57
"lobby.shrinkDaysHint": "First shrink after this many midnights, then again each time that many days pass, until the arena reaches its minimum size.",58
"lobby.ceasefire": "Forced cease-fire hours",59
"lobby.ceasefireHint": "During these hours (Europe/Amsterdam) no one may shoot. Moving, giving action points and upgrading range remain allowed. Periods may wrap around midnight.",60
"lobby.ceasefireAdd": "Add period",61
"lobby.ceasefireRemove": "Remove",62
"lobby.ceasefireStart": "From",63
"lobby.ceasefireEnd": "Until",64
"lobby.ceasefireEmpty": "No periods yet. Add one, or drag a slice on the clock.",65
"lobby.ceasefireClock": "24-hour clock. Drag the handles or paint a slice; red is cease-fire, gold is open fire. Times are Europe/Amsterdam.",66
"lobby.apLoot": "Loot action points on a kill",67
"lobby.apLootHint": "When you eliminate a player with a shot, you receive their remaining action points. Surrender and the shrinking arena do not transfer points. Off by default.",68
"lobby.apTime": "Daily action points at",69
"lobby.apTimeHint": "Europe/Amsterdam. Action points, jury awards and arena shrinks all happen at this time each day. Default 00:00.",70
"lobby.visibility": "Visibility",71
"lobby.visibilityHint": "Who can see what. You always see your own lives, action points and range. Movement is always public. The server hides everything else from each viewer; hidden events do not appear on the timeline at all.",72
"lobby.visShots": "Shots",73
"lobby.visShotsPublic": "Public",74
"lobby.visShotsElimPublic": "Only eliminating shots are public",75
"lobby.visShotsKnownTarget": "Known to the target",76
"lobby.visShotsElimKnownTarget": "Only eliminating shots are known to the target",77
"lobby.visGifts": "Gifts",78
"lobby.visGiftsPublic": "Public",79
"lobby.visGiftsKnownRecipient": "Known to the recipient",80
"lobby.visGiftsAnonymous": "Anonymous — the recipient gets the points but must deduce who gave them",81
"lobby.visAp": "Action-point totals",82
"lobby.visApPublic": "Public",83
"lobby.visApHidden": "Hidden",84
"lobby.visRange": "Range",85
"lobby.visRangePublic": "Public",86
"lobby.visRangeInRange": "Known to players within range",87
"lobby.visRangeHidden": "Hidden",88
"lobby.visLives": "Lives",89
"lobby.visLivesPublic": "Public",90
"lobby.visLivesHidden": "Hidden",91
"info.hidden": "Hidden",92
"lobby.waiting": "Waiting for the host to start the game.",93
"lobby.back": "Back",94
"lobby.code": "Code",95
"lobby.playerCount.one": "{n} player",96
"lobby.playerCount.other": "{n} players",97
"lobby.playerCount.few": "{n} players",98
"lobby.playerCount.many": "{n} players",99
"game.day": "Day {n}",100
"game.nextAp": "Next action points",101
"game.lives": "Lives",102
"game.ap": "Action points",103
"game.range": "Range",104
"game.you": "You",105
"game.dead": "Out",106
"game.surrendered": "Surrendered",107
"game.winner": "{name} wins!",108
"game.youWin": "You win!",109
"game.draw": "The game ends in a draw.",110
"game.shrinkIn": "Arena shrinks in {n} days",111
"game.shrinkInDays.one": "Arena shrinks in {n} day",112
"game.shrinkInDays.other": "Arena shrinks in {n} days",113
"game.shrinkInDays.few": "Arena shrinks in {n} days",114
"game.shrinkInDays.many": "Arena shrinks in {n} days",115
"game.shrinkTomorrow": "Arena shrinks tomorrow",116
"game.shrinkToday": "Arena shrinks at the next distribution",117
"game.upgrade": "Upgrade range",118
"game.settings": "Settings",119
"game.surrender": "Surrender",120
"game.surrenderConfirm": "Surrender? You will be out of this game. This cannot be undone.",121
"game.surrenderConfirmBtn": "Yes, surrender",122
"game.surrenderCancel": "Cancel",123
"game.back": "Back to menu",124
"game.spectating": "You are out. You can still watch, send messages and, if the jury is on, vote.",125
"game.ceasefireLeft": "Time left in cease-fire",126
"game.ceasefireUntil": "Time until cease-fire",127
"game.ceasefireActive": "Cease-fire",128
"game.attackDisabled": "Attack",129
"game.attackDisabledReason": "Attack is not allowed during cease-fire hours.",130
"game.selectSelf": "Your tank is selected. Tap a highlighted tile to move, or upgrade your range.",131
"game.impassable": "Impassable",132
"game.willShrink": "This ring will shrink next",133
"opt.info": "Info",134
"opt.attack": "Attack",135
"opt.give": "Give action points",136
"opt.message": "Send message",137
"opt.close": "Close",138
"info.title": "Info",139
"info.lives": "Lives",140
"info.ap": "Action points",141
"info.range": "Range",142
"info.notes": "Your private notes",143
"info.notesHint": "Only you can see these notes. They are stored with your account.",144
"info.saveNotes": "Save notes",145
"info.saved": "Saved",146
"give.title": "Give action points",147
"give.howMany": "How many?",148
"give.send": "Give",149
"give.youHave": "You have {n}.",150
"chat.title": "Message {name}",151
"chat.placeholder": "Write a private message…",152
"chat.send": "Send",153
"chat.empty": "No messages yet.",154
"jury.title": "Jury",155
"jury.hint": "Vote for one living player. The player with the most votes gets an extra action point at the next distribution. You can change your vote until then. Other players cannot see your vote.",156
"jury.vote": "Vote",157
"jury.votedFor": "You voted for {name}",158
"jury.change": "Change vote",159
"timeline.play": "Play",160
"timeline.pause": "Pause",161
"timeline.live": "Live",162
"timeline.stepBack": "Step back",163
"timeline.stepForward": "Step forward",164
"timeline.event.start": "The game begins",165
"timeline.event.move": "{name} moves",166
"timeline.event.shoot": "{name} shoots {target}",167
"timeline.event.give": "{name} gives {n} action point(s) to {target}",168
"timeline.event.upgrade": "{name} upgrades range to {n}",169
"timeline.event.surrender": "{name} surrenders",170
"timeline.event.daily": "Day {n}: action points are distributed",171
"timeline.event.jury": "The jury awards a bonus to {name}",172
"timeline.event.juryTie": "The jury awards a bonus to {names}",173
"timeline.event.shrink": "The arena shrinks",174
"timeline.event.win": "{name} wins",175
"timeline.event.death": "{name} is out",176
"timeline.event.deathShot": "{name} is shot by {by}",177
"timeline.event.deathShrink": "{name} is caught by the shrinking arena",178
"timeline.event.deathCrushed": "{name} is crushed: no free tile left",179
"timeline.event.draw": "The game ends in a draw",180
"auth.unavailable": "Sign-in is temporarily unavailable.",181
"auth.backToGame": "Back to Allianties",182
"auth.failed": "Sign-in failed.",183
"auth.retry": "Try again",184
"auth.back": "Back",185
"lang.choose": "Choose language",186
"lang.current": "Language: {name}",187
"error.login": "Log in to continue.",188
"error.csrf": "Your session expired. Refresh the page and try again.",189
"error.not_host": "Only the host can do that.",190
"error.min_players": "You need at least two players to start.",191
"error.not_in_game": "You are not in this game.",192
"error.dead": "You are out of this game.",193
"error.no_ap": "You have no action points left.",194
"error.occupied": "That tile is occupied.",195
"error.impassable": "That tile is impassable.",196
"error.out_of_range": "That player is out of range.",197
"error.invalid_move": "That move is not allowed.",198
"error.game_started": "This game has already started.",199
"error.game_finished": "This game is over.",200
"error.lobby_full": "This lobby is full.",201
"error.unknown_code": "No lobby found with that code.",202
"error.cannot_vote": "You cannot vote now.",203
"error.bad_vote": "You can only vote for a living player.",204
"error.bad_give": "You cannot give that many action points.",205
"error.unknown_action": "Unknown action.",206
"error.ceasefire": "You cannot attack during cease-fire hours.",207
"error.generic": "Something went wrong. Please try again.",208
"error.serverStatus": "The server returned {status}."209
},210
"nl": {211
"app.name": "Allianties",212
"menu.tagline": "Een spel van geduld, allianties en goed getimede schoten.",213
"menu.login": "Inloggen",214
"menu.logout": "Uitloggen",215
"menu.loggedInAs": "Ingelogd als",216
"menu.localTest": "lokale test:",217
"menu.create": "Nieuwe lobby",218
"menu.join": "Deelnemen",219
"menu.codePlaceholder": "Code",220
"menu.myGames": "Jouw spellen",221
"menu.noGames": "Je hebt nog geen spellen. Start een lobby en nodig anderen uit.",222
"menu.authUnconfiguredHtml": "Inloggen is op deze server nog niet ingesteld. De callback <code>/allianties/callback.php</code> moet bij auth.timfalken.com worden geregistreerd, en het clientgeheim moet worden gezet.",223
"menu.guestHint": "Log in om een lobby te maken, spelers uit te nodigen en een blijvend spel te starten.",224
"menu.open": "Openen",225
"menu.continue": "Verder",226
"menu.statusLobby": "Lobby",227
"menu.statusRunning": "Bezig",228
"menu.statusFinished": "Afgelopen",229
"menu.youWon": "Jij won",230
"menu.draw": "Gelijkspel",231
"menu.winnerIs": "Winnaar: {name}",232
"menu.needLogin": "Log eerst in om te spelen.",233
"menu.players": "Spelers",234
"lobby.title": "Lobby",235
"lobby.invite": "Uitnodigen",236
"lobby.copy": "Kopieer link",237
"lobby.copied": "Gekopieerd",238
"lobby.shareHint": "Deel deze code of link. Spelers loggen in en doen mee.",239
"lobby.players": "Spelers",240
"lobby.start": "Start spel",241
"lobby.leave": "Lobby verlaten",242
"lobby.host": "Host",243
"lobby.you": "jij",244
"lobby.minPlayers": "Je hebt minstens twee spelers nodig om te starten.",245
"lobby.needTwo": "Wachten op minstens één speler extra…",246
"lobby.rules": "Regels",247
"lobby.jury": "Jury",248
"lobby.juryHint": "Dode spelers stemmen elke dag op een levende speler. Wie de meeste stemmen krijgt, ontvangt één extra actiepunt bij de volgende dagelijkse uitdeling. Bij een gelijke stand krijgt iedere gelijkstaande speler de bonus. Stemmen zijn geheim en tot dan toe te wijzigen.",249
"lobby.shrink": "Krimpend speelveld",250
"lobby.shrinkHint": "Na elk ingesteld aantal dagen wordt de buitenste ring bij de dagelijkse uitdeling onbegaanbaar. Spelers die erop staan verliezen een leven en worden naar binnen geduwd.",251
"lobby.shrinkDays": "Dagen tussen krimp",252
"lobby.shrinkDaysHint": "De eerste krimp na dit aantal middernachten, daarna opnieuw telkens na evenveel dagen, tot het veld zijn minimumgrootte heeft.",253
"lobby.ceasefire": "Gedwongen staakt-het-vuren",254
"lobby.ceasefireHint": "In deze uren (Europe/Amsterdam) mag niemand schieten. Verplaatsen, actiepunten geven en bereik upgraden blijft toegestaan. Periodes mogen over middernacht lopen.",255
"lobby.ceasefireAdd": "Periode toevoegen",256
"lobby.ceasefireRemove": "Verwijderen",257
"lobby.ceasefireStart": "Van",258
"lobby.ceasefireEnd": "Tot",259
"lobby.ceasefireEmpty": "Nog geen periodes. Voeg er een toe, of sleep een stuk op de klok.",260
"lobby.ceasefireClock": "24-uursklok. Sleep de handvatten of teken een stuk; rood is staakt-het-vuren, goud is vrij schieten. Tijden zijn Europe/Amsterdam.",261
"lobby.apLoot": "Actiepunten plunderen bij een kill",262
"lobby.apLootHint": "Als je een speler uitschakelt met een schot, ontvang je diens resterende actiepunten. Overgave en het krimpende speelveld geven geen punten. Standaard uit.",263
"lobby.apTime": "Dagelijkse actiepunten om",264
"lobby.apTimeHint": "Europe/Amsterdam. Actiepunten, jurybonussen en het krimpen van het veld gebeuren elke dag op dit tijdstip. Standaard 00:00.",265
"lobby.visibility": "Zichtbaarheid",266
"lobby.visibilityHint": "Wie wat kan zien. Je ziet altijd je eigen levens, actiepunten en bereik. Verplaatsingen zijn altijd openbaar. De server verbergt de rest per kijker; verborgen gebeurtenissen verschijnen helemaal niet op de tijdlijn.",267
"lobby.visShots": "Schoten",268
"lobby.visShotsPublic": "Openbaar",269
"lobby.visShotsElimPublic": "Alleen uitschakelende schoten zijn openbaar",270
"lobby.visShotsKnownTarget": "Alleen bekend bij het doelwit",271
"lobby.visShotsElimKnownTarget": "Alleen een uitschakelend schot is bekend bij het doelwit",272
"lobby.visGifts": "Giften",273
"lobby.visGiftsPublic": "Openbaar",274
"lobby.visGiftsKnownRecipient": "Alleen bekend bij de ontvanger",275
"lobby.visGiftsAnonymous": "Anoniem — de ontvanger krijgt de punten maar moet zelf afleiden van wie",276
"lobby.visAp": "Actiepuntentotalen",277
"lobby.visApPublic": "Openbaar",278
"lobby.visApHidden": "Verborgen",279
"lobby.visRange": "Bereik",280
"lobby.visRangePublic": "Openbaar",281
"lobby.visRangeInRange": "Bekend bij spelers binnen bereik",282
"lobby.visRangeHidden": "Verborgen",283
"lobby.visLives": "Levens",284
"lobby.visLivesPublic": "Openbaar",285
"lobby.visLivesHidden": "Verborgen",286
"info.hidden": "Verborgen",287
"lobby.waiting": "Wachten tot de host het spel start.",288
"lobby.back": "Terug",289
"lobby.code": "Code",290
"lobby.playerCount.one": "{n} speler",291
"lobby.playerCount.other": "{n} spelers",292
"lobby.playerCount.few": "{n} spelers",293
"lobby.playerCount.many": "{n} spelers",294
"game.day": "Dag {n}",295
"game.nextAp": "Volgende actiepunten",296
"game.lives": "Levens",297
"game.ap": "Actiepunten",298
"game.range": "Bereik",299
"game.you": "Jij",300
"game.dead": "Uitgeschakeld",301
"game.surrendered": "Overgegeven",302
"game.winner": "{name} wint!",303
"game.youWin": "Jij wint!",304
"game.draw": "Het spel eindigt in een gelijkspel.",305
"game.shrinkIn": "Het veld krimpt over {n} dagen",306
"game.shrinkInDays.one": "Het veld krimpt over {n} dag",307
"game.shrinkInDays.other": "Het veld krimpt over {n} dagen",308
"game.shrinkInDays.few": "Het veld krimpt over {n} dagen",309
"game.shrinkInDays.many": "Het veld krimpt over {n} dagen",310
"game.shrinkTomorrow": "Het veld krimpt morgen",311
"game.shrinkToday": "Het veld krimpt bij de volgende uitdeling",312
"game.upgrade": "Bereik vergroten",313
"game.settings": "Instellingen",314
"game.surrender": "Overgeven",315
"game.surrenderConfirm": "Overgeven? Je bent dan uit dit spel. Dit kun je niet ongedaan maken.",316
"game.surrenderConfirmBtn": "Ja, overgeven",317
"game.surrenderCancel": "Annuleren",318
"game.back": "Terug naar het menu",319
"game.spectating": "Je bent uitgeschakeld. Je kunt nog meekijken, berichten sturen en, als de jury aan staat, stemmen.",320
"game.ceasefireLeft": "Tijd over in het staakt-het-vuren",321
"game.ceasefireUntil": "Tijd tot het staakt-het-vuren",322
"game.ceasefireActive": "Staakt-het-vuren",323
"game.attackDisabled": "Aanvallen",324
"game.attackDisabledReason": "Aanvallen is niet toegestaan tijdens het staakt-het-vuren.",325
"game.selectSelf": "Jouw tank is geselecteerd. Tik op een gemarkeerd vakje om te bewegen, of vergroot je bereik.",326
"game.impassable": "Onbegaanbaar",327
"game.willShrink": "Deze ring krimpt als volgende",328
"opt.info": "Info",329
"opt.attack": "Aanvallen",330
"opt.give": "Actiepunten geven",331
"opt.message": "Bericht sturen",332
"opt.close": "Sluiten",333
"info.title": "Info",334
"info.lives": "Levens",335
"info.ap": "Actiepunten",336
"info.range": "Bereik",337
"info.notes": "Jouw privénotities",338
"info.notesHint": "Alleen jij ziet deze notities. Ze worden bij jouw account bewaard.",339
"info.saveNotes": "Notities opslaan",340
"info.saved": "Opgeslagen",341
"give.title": "Actiepunten geven",342
"give.howMany": "Hoeveel?",343
"give.send": "Geven",344
"give.youHave": "Je hebt er {n}.",345
"chat.title": "Bericht aan {name}",346
"chat.placeholder": "Schrijf een privébericht…",347
"chat.send": "Versturen",348
"chat.empty": "Nog geen berichten.",349
"jury.title": "Jury",350
"jury.hint": "Stem op één levende speler. Wie de meeste stemmen krijgt, ontvangt een extra actiepunt bij de volgende uitdeling. Je kunt je stem tot dan toe wijzigen. Andere spelers zien je stem niet.",351
"jury.vote": "Stemmen",352
"jury.votedFor": "Je stemde op {name}",353
"jury.change": "Stem wijzigen",354
"timeline.play": "Afspelen",355
"timeline.pause": "Pauzeren",356
"timeline.live": "Live",357
"timeline.stepBack": "Een stap terug",358
"timeline.stepForward": "Een stap vooruit",359
"timeline.event.start": "Het spel begint",360
"timeline.event.move": "{name} verplaatst zich",361
"timeline.event.shoot": "{name} schiet op {target}",362
"timeline.event.give": "{name} geeft {n} actiepunt(en) aan {target}",363
"timeline.event.upgrade": "{name} vergroot het bereik naar {n}",364
"timeline.event.surrender": "{name} geeft zich over",365
"timeline.event.daily": "Dag {n}: actiepunten worden uitgedeeld",366
"timeline.event.jury": "De jury kent een bonus toe aan {name}",367
"timeline.event.juryTie": "De jury kent een bonus toe aan {names}",368
"timeline.event.shrink": "Het speelveld krimpt",369
"timeline.event.win": "{name} wint",370
"timeline.event.death": "{name} is uitgeschakeld",371
"timeline.event.deathShot": "{name} wordt neergeschoten door {by}",372
"timeline.event.deathShrink": "{name} wordt geraakt door het krimpende veld",373
"timeline.event.deathCrushed": "{name} wordt vermorzeld: geen vrij vakje meer",374
"timeline.event.draw": "Het spel eindigt in een gelijkspel",375
"auth.unavailable": "Inloggen is tijdelijk niet beschikbaar.",376
"auth.backToGame": "Terug naar Allianties",377
"auth.failed": "Inloggen is mislukt.",378
"auth.retry": "Opnieuw proberen",379
"auth.back": "Terug",380
"lang.choose": "Kies een taal",381
"lang.current": "Taal: {name}",382
"error.login": "Log in om verder te gaan.",383
"error.csrf": "Je sessie is verlopen. Vernieuw de pagina en probeer het opnieuw.",384
"error.not_host": "Alleen de host kan dat doen.",385
"error.min_players": "Je hebt minstens twee spelers nodig om te starten.",386
"error.not_in_game": "Je zit niet in dit spel.",387
"error.dead": "Je bent uit dit spel.",388
"error.no_ap": "Je hebt geen actiepunten meer.",389
"error.occupied": "Dat vakje is bezet.",390
"error.impassable": "Dat vakje is onbegaanbaar.",391
"error.out_of_range": "Die speler is buiten bereik.",392
"error.invalid_move": "Die zet is niet toegestaan.",393
"error.game_started": "Dit spel is al begonnen.",394
"error.game_finished": "Dit spel is afgelopen.",395
"error.lobby_full": "Deze lobby is vol.",396
"error.unknown_code": "Geen lobby gevonden met die code.",397
"error.cannot_vote": "Je kunt nu niet stemmen.",398
"error.bad_vote": "Je kunt alleen op een levende speler stemmen.",399
"error.bad_give": "Zoveel actiepunten kun je niet geven.",400
"error.unknown_action": "Onbekende actie.",401
"error.ceasefire": "Je kunt niet aanvallen tijdens het staakt-het-vuren.",402
"error.generic": "Er ging iets mis. Probeer het opnieuw.",403
"error.serverStatus": "De server gaf {status}."404
},405
"de": {406
"app.name": "Allianties",407
"menu.tagline": "Ein Spiel aus Geduld, Allianzen und gut getimten Schüssen.",408
"menu.login": "Anmelden",409
"menu.logout": "Abmelden",410
"menu.loggedInAs": "Angemeldet als",411
"menu.localTest": "lokaler Test:",412
"menu.create": "Neue Lobby",413
"menu.join": "Beitreten",414
"menu.codePlaceholder": "Code",415
"menu.myGames": "Deine Spiele",416
"menu.noGames": "Du hast noch keine Spiele. Eröffne eine Lobby und lade andere ein.",417
"menu.authUnconfiguredHtml": "Die Anmeldung ist auf diesem Server noch nicht eingerichtet. Der Callback <code>/allianties/callback.php</code> muss bei auth.timfalken.com registriert und das Client-Geheimnis konfiguriert werden.",418
"menu.guestHint": "Melde dich an, um eine Lobby zu erstellen, Spieler einzuladen und ein dauerhaftes Spiel zu starten.",419
"menu.open": "Öffnen",420
"menu.continue": "Weiter",421
"menu.statusLobby": "Lobby",422
"menu.statusRunning": "Läuft",423
"menu.statusFinished": "Beendet",424
"menu.youWon": "Du hast gewonnen",425
"menu.draw": "Unentschieden",426
"menu.winnerIs": "Gewinner: {name}",427
"menu.needLogin": "Melde dich zuerst an, um zu spielen.",428
"menu.players": "Spieler",429
"lobby.title": "Lobby",430
"lobby.invite": "Einladen",431
"lobby.copy": "Link kopieren",432
"lobby.copied": "Kopiert",433
"lobby.shareHint": "Teile diesen Code oder Link. Spieler melden sich an und treten bei.",434
"lobby.players": "Spieler",435
"lobby.start": "Spiel starten",436
"lobby.leave": "Lobby verlassen",437
"lobby.host": "Gastgeber",438
"lobby.you": "du",439
"lobby.minPlayers": "Du brauchst mindestens zwei Spieler, um zu starten.",440
"lobby.needTwo": "Warte auf mindestens einen weiteren Spieler…",441
"lobby.rules": "Regeln",442
"lobby.jury": "Jury",443
"lobby.juryHint": "Tote Spieler stimmen täglich für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten täglichen Verteilung einen Extra-Aktionspunkt. Bei Gleichstand erhält jeder gleichauf liegende Spieler den Bonus. Stimmen sind geheim und bis dahin änderbar.",444
"lobby.shrink": "Schrumpfendes Spielfeld",445
"lobby.shrinkHint": "Nach einer festgelegten Anzahl von Tagen wird der äußere Ring bei der täglichen Verteilung unpassierbar. Spieler, die darauf stehen, verlieren ein Leben und werden nach innen geschoben.",446
"lobby.shrinkDays": "Tage zwischen Schrumpfungen",447
"lobby.shrinkDaysHint": "Erste Schrumpfung nach so vielen Mitternächten, danach erneut nach jeweils ebenso vielen Tagen, bis das Feld seine Mindestgröße erreicht.",448
"lobby.ceasefire": "Erzwungene Waffenruhe",449
"lobby.ceasefireHint": "In diesen Stunden (Europe/Amsterdam) darf niemand schießen. Bewegen, Aktionspunkte abgeben und die Reichweite erhöhen bleiben erlaubt. Zeiträume dürfen über Mitternacht gehen.",450
"lobby.ceasefireAdd": "Zeitraum hinzufügen",451
"lobby.ceasefireRemove": "Entfernen",452
"lobby.ceasefireStart": "Von",453
"lobby.ceasefireEnd": "Bis",454
"lobby.ceasefireEmpty": "Noch keine Zeiträume. Füge einen hinzu oder ziehe ein Segment auf der Uhr.",455
"lobby.ceasefireClock": "24-Stunden-Uhr. Ziehe die Griffe oder male ein Segment; rot ist Waffenruhe, gold ist Feuer frei. Zeiten sind Europe/Amsterdam.",456
"lobby.apLoot": "Aktionspunkte bei einem Kill erbeuten",457
"lobby.apLootHint": "Wenn du einen Spieler mit einem Schuss ausschaltest, erhältst du dessen verbleibende Aktionspunkte. Aufgabe und das schrumpfende Feld übertragen keine Punkte. Standardmäßig aus.",458
"lobby.apTime": "Tägliche Aktionspunkte um",459
"lobby.apTimeHint": "Europe/Amsterdam. Aktionspunkte, Jury-Boni und das Schrumpfen des Feldes finden jeden Tag zu dieser Uhrzeit statt. Standard 00:00.",460
"lobby.visibility": "Sichtbarkeit",461
"lobby.visibilityHint": "Wer was sehen kann. Du siehst immer deine eigenen Leben, Aktionspunkte und Reichweite. Bewegungen sind immer öffentlich. Der Server blendet alles andere je Betrachter aus; versteckte Ereignisse erscheinen gar nicht auf der Zeitleiste.",462
"lobby.visShots": "Schüsse",463
"lobby.visShotsPublic": "Öffentlich",464
"lobby.visShotsElimPublic": "Nur ausschaltende Schüsse sind öffentlich",465
"lobby.visShotsKnownTarget": "Nur dem Ziel bekannt",466
"lobby.visShotsElimKnownTarget": "Nur ein ausschaltender Schuss ist dem Ziel bekannt",467
"lobby.visGifts": "Geschenke",468
"lobby.visGiftsPublic": "Öffentlich",469
"lobby.visGiftsKnownRecipient": "Nur dem Empfänger bekannt",470
"lobby.visGiftsAnonymous": "Anonym — der Empfänger erhält die Punkte, muss den Geber aber selbst ableiten",471
"lobby.visAp": "Aktionspunkte-Stand",472
"lobby.visApPublic": "Öffentlich",473
"lobby.visApHidden": "Verborgen",474
"lobby.visRange": "Reichweite",475
"lobby.visRangePublic": "Öffentlich",476
"lobby.visRangeInRange": "Bekannt für Spieler in Reichweite",477
"lobby.visRangeHidden": "Verborgen",478
"lobby.visLives": "Leben",479
"lobby.visLivesPublic": "Öffentlich",480
"lobby.visLivesHidden": "Verborgen",481
"info.hidden": "Verborgen",482
"lobby.waiting": "Warte, bis der Gastgeber das Spiel startet.",483
"lobby.back": "Zurück",484
"lobby.code": "Code",485
"lobby.playerCount.one": "{n} Spieler",486
"lobby.playerCount.other": "{n} Spieler",487
"lobby.playerCount.few": "{n} Spieler",488
"lobby.playerCount.many": "{n} Spieler",489
"game.day": "Tag {n}",490
"game.nextAp": "Nächste Aktionspunkte",491
"game.lives": "Leben",492
"game.ap": "Aktionspunkte",493
"game.range": "Reichweite",494
"game.you": "Du",495
"game.dead": "Ausgeschieden",496
"game.surrendered": "Aufgegeben",497
"game.winner": "{name} gewinnt!",498
"game.youWin": "Du gewinnst!",499
"game.draw": "Das Spiel endet unentschieden.",500
"game.shrinkIn": "Das Feld schrumpft in {n} Tagen",501
"game.shrinkInDays.one": "Das Feld schrumpft in {n} Tag",502
"game.shrinkInDays.other": "Das Feld schrumpft in {n} Tagen",503
"game.shrinkInDays.few": "Das Feld schrumpft in {n} Tagen",504
"game.shrinkInDays.many": "Das Feld schrumpft in {n} Tagen",505
"game.shrinkTomorrow": "Das Feld schrumpft morgen",506
"game.shrinkToday": "Das Feld schrumpft bei der nächsten Verteilung",507
"game.upgrade": "Reichweite erhöhen",508
"game.settings": "Einstellungen",509
"game.surrender": "Aufgeben",510
"game.surrenderConfirm": "Aufgeben? Du scheidest aus diesem Spiel aus. Das lässt sich nicht rückgängig machen.",511
"game.surrenderConfirmBtn": "Ja, aufgeben",512
"game.surrenderCancel": "Abbrechen",513
"game.back": "Zurück zum Menü",514
"game.spectating": "Du bist ausgeschieden. Du kannst weiterhin zuschauen, Nachrichten senden und, wenn die Jury an ist, abstimmen.",515
"game.ceasefireLeft": "Verbleibende Waffenruhe",516
"game.ceasefireUntil": "Zeit bis zur Waffenruhe",517
"game.ceasefireActive": "Waffenruhe",518
"game.attackDisabled": "Angreifen",519
"game.attackDisabledReason": "Angreifen ist während der Waffenruhe nicht erlaubt.",520
"game.selectSelf": "Dein Panzer ist ausgewählt. Tippe auf ein markiertes Feld, um dich zu bewegen, oder erhöhe deine Reichweite.",521
"game.impassable": "Unpassierbar",522
"game.willShrink": "Dieser Ring schrumpft als Nächstes",523
"opt.info": "Info",524
"opt.attack": "Angreifen",525
"opt.give": "Aktionspunkte geben",526
"opt.message": "Nachricht senden",527
"opt.close": "Schließen",528
"info.title": "Info",529
"info.lives": "Leben",530
"info.ap": "Aktionspunkte",531
"info.range": "Reichweite",532
"info.notes": "Deine privaten Notizen",533
"info.notesHint": "Nur du kannst diese Notizen sehen. Sie werden bei deinem Konto gespeichert.",534
"info.saveNotes": "Notizen speichern",535
"info.saved": "Gespeichert",536
"give.title": "Aktionspunkte geben",537
"give.howMany": "Wie viele?",538
"give.send": "Geben",539
"give.youHave": "Du hast {n}.",540
"chat.title": "Nachricht an {name}",541
"chat.placeholder": "Schreibe eine private Nachricht…",542
"chat.send": "Senden",543
"chat.empty": "Noch keine Nachrichten.",544
"jury.title": "Jury",545
"jury.hint": "Stimme für einen lebenden Spieler. Wer die meisten Stimmen erhält, bekommt bei der nächsten Verteilung einen Extra-Aktionspunkt. Du kannst deine Stimme bis dahin ändern. Andere Spieler sehen deine Stimme nicht.",546
"jury.vote": "Abstimmen",547
"jury.votedFor": "Du hast für {name} gestimmt",548
"jury.change": "Stimme ändern",549
"timeline.play": "Abspielen",550
"timeline.pause": "Pause",551
"timeline.live": "Live",552
"timeline.stepBack": "Einen Schritt zurück",553
"timeline.stepForward": "Einen Schritt vor",554
"timeline.event.start": "Das Spiel beginnt",555
"timeline.event.move": "{name} bewegt sich",556
"timeline.event.shoot": "{name} schießt auf {target}",557
"timeline.event.give": "{name} gibt {n} Aktionspunkt(e) an {target}",558
"timeline.event.upgrade": "{name} erhöht die Reichweite auf {n}",559
"timeline.event.surrender": "{name} gibt auf",560
"timeline.event.daily": "Tag {n}: Aktionspunkte werden verteilt",561
"timeline.event.jury": "Die Jury vergibt einen Bonus an {name}",562
"timeline.event.juryTie": "Die Jury vergibt einen Bonus an {names}",563
"timeline.event.shrink": "Das Spielfeld schrumpft",564
"timeline.event.win": "{name} gewinnt",565
"timeline.event.death": "{name} scheidet aus",566
"timeline.event.deathShot": "{name} wird von {by} erschossen",567
"timeline.event.deathShrink": "{name} wird vom schrumpfenden Feld erfasst",568
"timeline.event.deathCrushed": "{name} wird zerdrückt: kein freies Feld mehr",569
"timeline.event.draw": "Das Spiel endet unentschieden",570
"auth.unavailable": "Die Anmeldung ist vorübergehend nicht verfügbar.",571
"auth.backToGame": "Zurück zu Allianties",572
"auth.failed": "Anmeldung fehlgeschlagen.",573
"auth.retry": "Erneut versuchen",574
"auth.back": "Zurück",575
"lang.choose": "Sprache wählen",576
"lang.current": "Sprache: {name}",577
"error.login": "Melde dich an, um fortzufahren.",578
"error.csrf": "Deine Sitzung ist abgelaufen. Aktualisiere die Seite und versuche es erneut.",579
"error.not_host": "Das kann nur der Gastgeber tun.",580
"error.min_players": "Du brauchst mindestens zwei Spieler, um zu starten.",581
"error.not_in_game": "Du bist nicht in diesem Spiel.",582
"error.dead": "Du bist aus diesem Spiel ausgeschieden.",583
"error.no_ap": "Du hast keine Aktionspunkte mehr.",584
"error.occupied": "Dieses Feld ist besetzt.",585
"error.impassable": "Dieses Feld ist unpassierbar.",586
"error.out_of_range": "Dieser Spieler ist außer Reichweite.",587
"error.invalid_move": "Dieser Zug ist nicht erlaubt.",588
"error.game_started": "Dieses Spiel hat bereits begonnen.",589
"error.game_finished": "Dieses Spiel ist beendet.",590
"error.lobby_full": "Diese Lobby ist voll.",591
"error.unknown_code": "Keine Lobby mit diesem Code gefunden.",592
"error.cannot_vote": "Du kannst jetzt nicht abstimmen.",593
"error.bad_vote": "Du kannst nur für einen lebenden Spieler stimmen.",594
"error.bad_give": "So viele Aktionspunkte kannst du nicht abgeben.",595
"error.unknown_action": "Unbekannte Aktion.",596
"error.ceasefire": "Während der Waffenruhe kannst du nicht angreifen.",597
"error.generic": "Etwas ist schiefgegangen. Bitte versuche es erneut.",598
"error.serverStatus": "Der Server antwortete mit {status}."599
},600
"fr": {601
"app.name": "Allianties",602
"menu.tagline": "Un jeu de patience, d'alliances et de tirs bien calculés.",603
"menu.login": "Connexion",604
"menu.logout": "Déconnexion",605
"menu.loggedInAs": "Connecté en tant que",606
"menu.localTest": "test local :",607
"menu.create": "Nouveau salon",608
"menu.join": "Rejoindre",609
"menu.codePlaceholder": "Code",610
"menu.myGames": "Vos parties",611
"menu.noGames": "Vous n'avez pas encore de partie. Créez un salon et invitez d'autres joueurs.",612
"menu.authUnconfiguredHtml": "La connexion n'est pas encore configurée sur ce serveur. Le callback <code>/allianties/callback.php</code> doit être enregistré sur auth.timfalken.com, et le secret client doit être défini.",613
"menu.guestHint": "Connectez-vous pour créer un salon, inviter des joueurs et lancer une partie durable.",614
"menu.open": "Ouvrir",615
"menu.continue": "Continuer",616
"menu.statusLobby": "Salon",617
"menu.statusRunning": "En cours",618
"menu.statusFinished": "Terminée",619
"menu.youWon": "Vous avez gagné",620
"menu.draw": "Match nul",621
"menu.winnerIs": "Vainqueur : {name}",622
"menu.needLogin": "Connectez-vous d'abord pour jouer.",623
"menu.players": "Joueurs",624
"lobby.title": "Salon",625
"lobby.invite": "Inviter",626
"lobby.copy": "Copier le lien",627
"lobby.copied": "Copié",628
"lobby.shareHint": "Partagez ce code ou ce lien. Les joueurs se connectent et rejoignent la partie.",629
"lobby.players": "Joueurs",630
"lobby.start": "Lancer la partie",631
"lobby.leave": "Quitter le salon",632
"lobby.host": "Hôte",633
"lobby.you": "vous",634
"lobby.minPlayers": "Il faut au moins deux joueurs pour commencer.",635
"lobby.needTwo": "En attente d'au moins un joueur de plus…",636
"lobby.rules": "Règles",637
"lobby.jury": "Jury",638
"lobby.juryHint": "Les joueurs éliminés votent chaque jour pour un joueur vivant. Celui qui recueille le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution quotidienne. En cas d'égalité, chaque joueur à égalité reçoit le bonus. Les votes sont secrets et modifiables jusque-là.",639
"lobby.shrink": "Arène rétrécissante",640
"lobby.shrinkHint": "Après un nombre de jours réglable, l'anneau extérieur devient infranchissable à la distribution quotidienne. Les joueurs qui s'y trouvent perdent une vie et sont poussés vers l'intérieur.",641
"lobby.shrinkDays": "Jours entre les rétrécissements",642
"lobby.shrinkDaysHint": "Premier rétrécissement après autant de minuits, puis de nouveau tous les autant de jours, jusqu'à la taille minimale de l'arène.",643
"lobby.ceasefire": "Heures de cessez-le-feu forcé",644
"lobby.ceasefireHint": "Pendant ces heures (Europe/Amsterdam), personne ne peut tirer. Se déplacer, donner des points d'action et améliorer la portée restent autorisés. Les plages peuvent chevaucher minuit.",645
"lobby.ceasefireAdd": "Ajouter une plage",646
"lobby.ceasefireRemove": "Supprimer",647
"lobby.ceasefireStart": "De",648
"lobby.ceasefireEnd": "À",649
"lobby.ceasefireEmpty": "Aucune plage pour l'instant. Ajoutez-en une, ou dessinez un secteur sur l'horloge.",650
"lobby.ceasefireClock": "Horloge 24 heures. Faites glisser les poignées ou dessinez un secteur ; le rouge est le cessez-le-feu, l'or le feu autorisé. Heures en Europe/Amsterdam.",651
"lobby.apLoot": "Prendre les points d’action lors d’une élimination",652
"lobby.apLootHint": "Lorsque vous éliminez un joueur par un tir, vous recevez ses points d’action restants. Abandon et arène qui rétrécit ne transfèrent rien. Désactivé par défaut.",653
"lobby.apTime": "Points d’action quotidiens à",654
"lobby.apTimeHint": "Europe/Amsterdam. Les points d’action, les bonus du jury et le rétrécissement ont lieu chaque jour à cette heure. 00:00 par défaut.",655
"lobby.visibility": "Visibilité",656
"lobby.visibilityHint": "Qui voit quoi. Vous voyez toujours vos propres vies, points d’action et portée. Les déplacements sont toujours publics. Le serveur masque le reste pour chaque spectateur ; les événements cachés n’apparaissent pas du tout sur la timeline.",657
"lobby.visShots": "Tirs",658
"lobby.visShotsPublic": "Public",659
"lobby.visShotsElimPublic": "Seuls les tirs éliminatoires sont publics",660
"lobby.visShotsKnownTarget": "Connu de la cible",661
"lobby.visShotsElimKnownTarget": "Seul un tir éliminatoire est connu de la cible",662
"lobby.visGifts": "Dons",663
"lobby.visGiftsPublic": "Public",664
"lobby.visGiftsKnownRecipient": "Connu du destinataire",665
"lobby.visGiftsAnonymous": "Anonyme — le destinataire reçoit les points mais doit déduire de qui ils viennent",666
"lobby.visAp": "Totaux de points d’action",667
"lobby.visApPublic": "Public",668
"lobby.visApHidden": "Caché",669
"lobby.visRange": "Portée",670
"lobby.visRangePublic": "Public",671
"lobby.visRangeInRange": "Connu des joueurs à portée",672
"lobby.visRangeHidden": "Caché",673
"lobby.visLives": "Vies",674
"lobby.visLivesPublic": "Public",675
"lobby.visLivesHidden": "Caché",676
"info.hidden": "Caché",677
"lobby.waiting": "En attente que l'hôte lance la partie.",678
"lobby.back": "Retour",679
"lobby.code": "Code",680
"lobby.playerCount.one": "{n} joueur",681
"lobby.playerCount.other": "{n} joueurs",682
"lobby.playerCount.few": "{n} joueurs",683
"lobby.playerCount.many": "{n} joueurs",684
"game.day": "Jour {n}",685
"game.nextAp": "Prochains points d'action",686
"game.lives": "Vies",687
"game.ap": "Points d'action",688
"game.range": "Portée",689
"game.you": "Vous",690
"game.dead": "Éliminé",691
"game.surrendered": "A abandonné",692
"game.winner": "{name} gagne !",693
"game.youWin": "Vous gagnez !",694
"game.draw": "La partie se termine par un match nul.",695
"game.shrinkIn": "L'arène rétrécit dans {n} jours",696
"game.shrinkInDays.one": "L'arène rétrécit dans {n} jour",697
"game.shrinkInDays.other": "L'arène rétrécit dans {n} jours",698
"game.shrinkInDays.few": "L'arène rétrécit dans {n} jours",699
"game.shrinkInDays.many": "L'arène rétrécit dans {n} jours",700
"game.shrinkTomorrow": "L'arène rétrécit demain",701
"game.shrinkToday": "L'arène rétrécit à la prochaine distribution",702
"game.upgrade": "Augmenter la portée",703
"game.settings": "Paramètres",704
"game.surrender": "Abandonner",705
"game.surrenderConfirm": "Abandonner ? Vous serez éliminé de cette partie. Cette action est irréversible.",706
"game.surrenderConfirmBtn": "Oui, abandonner",707
"game.surrenderCancel": "Annuler",708
"game.back": "Retour au menu",709
"game.spectating": "Vous êtes éliminé. Vous pouvez encore regarder, envoyer des messages et, si le jury est actif, voter.",710
"game.ceasefireLeft": "Temps restant de cessez-le-feu",711
"game.ceasefireUntil": "Temps avant le cessez-le-feu",712
"game.ceasefireActive": "Cessez-le-feu",713
"game.attackDisabled": "Attaquer",714
"game.attackDisabledReason": "Attaquer n'est pas autorisé pendant les heures de cessez-le-feu.",715
"game.selectSelf": "Votre tank est sélectionné. Touchez une case mise en évidence pour vous déplacer, ou augmentez votre portée.",716
"game.impassable": "Infranchissable",717
"game.willShrink": "Cet anneau rétrécira ensuite",718
"opt.info": "Infos",719
"opt.attack": "Attaquer",720
"opt.give": "Donner des points d'action",721
"opt.message": "Envoyer un message",722
"opt.close": "Fermer",723
"info.title": "Infos",724
"info.lives": "Vies",725
"info.ap": "Points d'action",726
"info.range": "Portée",727
"info.notes": "Vos notes privées",728
"info.notesHint": "Vous seul pouvez voir ces notes. Elles sont enregistrées avec votre compte.",729
"info.saveNotes": "Enregistrer les notes",730
"info.saved": "Enregistré",731
"give.title": "Donner des points d'action",732
"give.howMany": "Combien ?",733
"give.send": "Donner",734
"give.youHave": "Vous en avez {n}.",735
"chat.title": "Message à {name}",736
"chat.placeholder": "Écrire un message privé…",737
"chat.send": "Envoyer",738
"chat.empty": "Pas encore de messages.",739
"jury.title": "Jury",740
"jury.hint": "Votez pour un joueur vivant. Celui qui obtient le plus de voix reçoit un point d'action supplémentaire à la prochaine distribution. Vous pouvez changer votre vote jusque-là. Les autres joueurs ne voient pas votre vote.",741
"jury.vote": "Voter",742
"jury.votedFor": "Vous avez voté pour {name}",743
"jury.change": "Changer de vote",744
"timeline.play": "Lecture",745
"timeline.pause": "Pause",746
"timeline.live": "En direct",747
"timeline.stepBack": "Reculer d’un pas",748
"timeline.stepForward": "Avancer d’un pas",749
"timeline.event.start": "La partie commence",750
"timeline.event.move": "{name} se déplace",751
"timeline.event.shoot": "{name} tire sur {target}",752
"timeline.event.give": "{name} donne {n} point(s) d'action à {target}",753
"timeline.event.upgrade": "{name} porte sa portée à {n}",754
"timeline.event.surrender": "{name} abandonne",755
"timeline.event.daily": "Jour {n} : distribution des points d'action",756
"timeline.event.jury": "Le jury attribue un bonus à {name}",757
"timeline.event.juryTie": "Le jury attribue un bonus à {names}",758
"timeline.event.shrink": "L'arène rétrécit",759
"timeline.event.win": "{name} gagne",760
"timeline.event.death": "{name} est éliminé",761
"timeline.event.deathShot": "{name} est abattu par {by}",762
"timeline.event.deathShrink": "{name} est pris par l'arène qui rétrécit",763
"timeline.event.deathCrushed": "{name} est écrasé : plus aucune case libre",764
"timeline.event.draw": "La partie se termine par un match nul",765
"auth.unavailable": "La connexion est temporairement indisponible.",766
"auth.backToGame": "Retour à Allianties",767
"auth.failed": "Échec de la connexion.",768
"auth.retry": "Réessayer",769
"auth.back": "Retour",770
"lang.choose": "Choisir la langue",771
"lang.current": "Langue : {name}",772
"error.login": "Connectez-vous pour continuer.",773
"error.csrf": "Votre session a expiré. Actualisez la page et réessayez.",774
"error.not_host": "Seul l'hôte peut faire cela.",775
"error.min_players": "Il faut au moins deux joueurs pour commencer.",776
"error.not_in_game": "Vous n'êtes pas dans cette partie.",777
"error.dead": "Vous êtes éliminé de cette partie.",778
"error.no_ap": "Vous n'avez plus de points d'action.",779
"error.occupied": "Cette case est occupée.",780
"error.impassable": "Cette case est infranchissable.",781
"error.out_of_range": "Ce joueur est hors de portée.",782
"error.invalid_move": "Ce coup n'est pas autorisé.",783
"error.game_started": "Cette partie a déjà commencé.",784
"error.game_finished": "Cette partie est terminée.",785
"error.lobby_full": "Ce salon est complet.",786
"error.unknown_code": "Aucun salon trouvé avec ce code.",787
"error.cannot_vote": "Vous ne pouvez pas voter maintenant.",788
"error.bad_vote": "Vous ne pouvez voter que pour un joueur vivant.",789
"error.bad_give": "Vous ne pouvez pas donner autant de points d'action.",790
"error.unknown_action": "Action inconnue.",791
"error.ceasefire": "Vous ne pouvez pas attaquer pendant le cessez-le-feu.",792
"error.generic": "Un problème est survenu. Veuillez réessayer.",793
"error.serverStatus": "Le serveur a renvoyé {status}."794
},795
"ja": {796
"app.name": "Allianties",797
"menu.tagline": "忍耐、同盟、そして時機を逃さない一撃のゲーム。",798
"menu.login": "ログイン",799
"menu.logout": "ログアウト",800
"menu.loggedInAs": "ログイン中",801
"menu.localTest": "ローカルテスト:",802
"menu.create": "新しいロビー",803
"menu.join": "参加",804
"menu.codePlaceholder": "コード",805
"menu.myGames": "あなたのゲーム",806
"menu.noGames": "まだゲームがありません。ロビーを作って他の人を招待しましょう。",807
"menu.authUnconfiguredHtml": "このサーバーではまだログインが設定されていません。コールバック <code>/allianties/callback.php</code> を auth.timfalken.com に登録し、クライアントシークレットを設定する必要があります。",808
"menu.guestHint": "ログインすると、ロビーの作成、招待、長く続くゲームの開始ができます。",809
"menu.open": "開く",810
"menu.continue": "続ける",811
"menu.statusLobby": "ロビー",812
"menu.statusRunning": "プレイ中",813
"menu.statusFinished": "終了",814
"menu.youWon": "勝利",815
"menu.draw": "引き分け",816
"menu.winnerIs": "勝者:{name}",817
"menu.needLogin": "プレイするには、まずログインしてください。",818
"menu.players": "プレイヤー",819
"lobby.title": "ロビー",820
"lobby.invite": "招待",821
"lobby.copy": "リンクをコピー",822
"lobby.copied": "コピーしました",823
"lobby.shareHint": "このコードまたはリンクを共有してください。プレイヤーはログインして参加します。",824
"lobby.players": "プレイヤー",825
"lobby.start": "ゲームを開始",826
"lobby.leave": "ロビーを退出",827
"lobby.host": "ホスト",828
"lobby.you": "あなた",829
"lobby.minPlayers": "開始するには少なくとも2人必要です。",830
"lobby.needTwo": "あと少なくとも1人を待っています…",831
"lobby.rules": "ルール",832
"lobby.jury": "陪審",833
"lobby.juryHint": "脱落したプレイヤーは毎日、生存中のプレイヤー1人に投票します。最多得票のプレイヤーは、次の毎日配布で行動力を1つ余分に受け取ります。同票の場合は、同票の全員がボーナスを受け取ります。投票は秘密で、配布まで変更できます。",834
"lobby.shrink": "縮小する戦場",835
"lobby.shrinkHint": "設定した日数ごとに、毎日の配布のときに外周が通行不能になります。その上にいるプレイヤーはライフを1失い、内側へ押し出されます。",836
"lobby.shrinkDays": "縮小の間隔(日)",837
"lobby.shrinkDaysHint": "最初の縮小はこの回数の深夜のあと、その後同じ日数ごとに繰り返し、戦場が最小サイズになるまで続きます。",838
"lobby.ceasefire": "強制停戦時間",839
"lobby.ceasefireHint": "この時間帯(Europe/Amsterdam)は誰も撃てません。移動、行動力の譲渡、射程の強化は可能です。時間帯は深夜をまたげます。",840
"lobby.ceasefireAdd": "時間帯を追加",841
"lobby.ceasefireRemove": "削除",842
"lobby.ceasefireStart": "開始",843
"lobby.ceasefireEnd": "終了",844
"lobby.ceasefireEmpty": "まだ時間帯がありません。追加するか、時計の上で扇形をドラッグしてください。",845
"lobby.ceasefireClock": "24時間時計。ハンドルをドラッグするか扇形を描きます。赤は停戦、金は攻撃可能。時刻は Europe/Amsterdam です。",846
"lobby.apLoot": "倒した相手のアクションポイントを奪う",847
"lobby.apLootHint": "射撃で相手を倒すと、残っていたアクションポイントを得ます。投降や縮小する戦場では移りません。既定はオフです。",848
"lobby.apTime": "毎日のアクションポイント配布時刻",849
"lobby.apTimeHint": "Europe/Amsterdam。アクションポイント、陪審のボーナス、戦場の縮小は毎日この時刻に行われます。既定は 00:00 です。",850
"lobby.visibility": "公開範囲",851
"lobby.visibilityHint": "誰が何を見られるか。自分のライフ、アクションポイント、射程は常に見えます。移動は常に公開です。サーバーが閲覧者ごとにそれ以外を隠し、隠された出来事はタイムラインに一切表示されません。",852
"lobby.visShots": "射撃",853
"lobby.visShotsPublic": "公開",854
"lobby.visShotsElimPublic": "公開されるのは倒した射撃のみ",855
"lobby.visShotsKnownTarget": "対象にのみ分かる",856
"lobby.visShotsElimKnownTarget": "対象に分かるのは倒した射撃のみ",857
"lobby.visGifts": "譲渡",858
"lobby.visGiftsPublic": "公開",859
"lobby.visGiftsKnownRecipient": "受け手にのみ分かる",860
"lobby.visGiftsAnonymous": "匿名 — 受け手はポイントを得るが、誰からかは自分で推論する",861
"lobby.visAp": "アクションポイント合計",862
"lobby.visApPublic": "公開",863
"lobby.visApHidden": "非公開",864
"lobby.visRange": "射程",865
"lobby.visRangePublic": "公開",866
"lobby.visRangeInRange": "射程内のプレイヤーに分かる",867
"lobby.visRangeHidden": "非公開",868
"lobby.visLives": "ライフ",869
"lobby.visLivesPublic": "公開",870
"lobby.visLivesHidden": "非公開",871
"info.hidden": "非公開",872
"lobby.waiting": "ホストがゲームを開始するのを待っています。",873
"lobby.back": "戻る",874
"lobby.code": "コード",875
"lobby.playerCount.one": "{n}人のプレイヤー",876
"lobby.playerCount.other": "{n}人のプレイヤー",877
"lobby.playerCount.few": "{n}人のプレイヤー",878
"lobby.playerCount.many": "{n}人のプレイヤー",879
"game.day": "{n}日目",880
"game.nextAp": "次の行動力",881
"game.lives": "ライフ",882
"game.ap": "行動力",883
"game.range": "射程",884
"game.you": "あなた",885
"game.dead": "脱落",886
"game.surrendered": "降伏",887
"game.winner": "{name}の勝利!",888
"game.youWin": "あなたの勝利!",889
"game.draw": "引き分けでゲーム終了です。",890
"game.shrinkIn": "戦場は{n}日後に縮小します",891
"game.shrinkInDays.one": "戦場は{n}日後に縮小します",892
"game.shrinkInDays.other": "戦場は{n}日後に縮小します",893
"game.shrinkInDays.few": "戦場は{n}日後に縮小します",894
"game.shrinkInDays.many": "戦場は{n}日後に縮小します",895
"game.shrinkTomorrow": "戦場は明日縮小します",896
"game.shrinkToday": "戦場は次の配布時に縮小します",897
"game.upgrade": "射程を伸ばす",898
"game.settings": "設定",899
"game.surrender": "降伏する",900
"game.surrenderConfirm": "降伏しますか?このゲームから脱落します。取り消すことはできません。",901
"game.surrenderConfirmBtn": "はい、降伏する",902
"game.surrenderCancel": "キャンセル",903
"game.back": "メニューに戻る",904
"game.spectating": "あなたは脱落しました。観戦、メッセージ送信、陪審がオンなら投票はできます。",905
"game.ceasefireLeft": "停戦の残り時間",906
"game.ceasefireUntil": "停戦までの時間",907
"game.ceasefireActive": "停戦中",908
"game.attackDisabled": "攻撃",909
"game.attackDisabledReason": "停戦時間中は攻撃できません。",910
"game.selectSelf": "自分の戦車が選ばれています。ハイライトされたマスをタップして移動するか、射程を伸ばしてください。",911
"game.impassable": "通行不能",912
"game.willShrink": "次に縮小する輪",913
"opt.info": "情報",914
"opt.attack": "攻撃",915
"opt.give": "行動力を渡す",916
"opt.message": "メッセージを送る",917
"opt.close": "閉じる",918
"info.title": "情報",919
"info.lives": "ライフ",920
"info.ap": "行動力",921
"info.range": "射程",922
"info.notes": "非公開のメモ",923
"info.notesHint": "このメモはあなただけが見られます。アカウントに保存されます。",924
"info.saveNotes": "メモを保存",925
"info.saved": "保存しました",926
"give.title": "行動力を渡す",927
"give.howMany": "いくつ?",928
"give.send": "渡す",929
"give.youHave": "あなたは{n}持っています。",930
"chat.title": "{name}へのメッセージ",931
"chat.placeholder": "非公開メッセージを書く…",932
"chat.send": "送信",933
"chat.empty": "まだメッセージはありません。",934
"jury.title": "陪審",935
"jury.hint": "生存中のプレイヤー1人に投票します。最多得票者は次の配布で行動力を1つ余分に得ます。それまで投票は変更できます。他のプレイヤーに投票は見えません。",936
"jury.vote": "投票する",937
"jury.votedFor": "{name}に投票しました",938
"jury.change": "投票を変更",939
"timeline.play": "再生",940
"timeline.pause": "一時停止",941
"timeline.live": "ライブ",942
"timeline.stepBack": "一つ戻る",943
"timeline.stepForward": "一つ進む",944
"timeline.event.start": "ゲーム開始",945
"timeline.event.move": "{name}が移動",946
"timeline.event.shoot": "{name}が{target}を撃つ",947
"timeline.event.give": "{name}が{target}に行動力を{n}渡す",948
"timeline.event.upgrade": "{name}が射程を{n}に伸ばす",949
"timeline.event.surrender": "{name}が降伏",950
"timeline.event.daily": "{n}日目:行動力の配布",951
"timeline.event.jury": "陪審が{name}にボーナスを与える",952
"timeline.event.juryTie": "陪審が{names}にボーナスを与える",953
"timeline.event.shrink": "戦場が縮小する",954
"timeline.event.win": "{name}の勝利",955
"timeline.event.death": "{name}が脱落",956
"timeline.event.deathShot": "{name}が{by}に撃たれて脱落",957
"timeline.event.deathShrink": "{name}が縮小する戦場に巻き込まれた",958
"timeline.event.deathCrushed": "{name}は押しつぶされた:空きマスがない",959
"timeline.event.draw": "引き分けで終了",960
"auth.unavailable": "ログインは一時的に利用できません。",961
"auth.backToGame": "Alliantiesに戻る",962
"auth.failed": "ログインに失敗しました。",963
"auth.retry": "再試行",964
"auth.back": "戻る",965
"lang.choose": "言語を選択",966
"lang.current": "言語:{name}",967
"error.login": "続けるにはログインしてください。",968
"error.csrf": "セッションの期限が切れました。ページを更新してもう一度お試しください。",969
"error.not_host": "ホストだけがそれを行えます。",970
"error.min_players": "開始するには少なくとも2人必要です。",971
"error.not_in_game": "このゲームには参加していません。",972
"error.dead": "このゲームから脱落しています。",973
"error.no_ap": "行動力が残っていません。",974
"error.occupied": "そのマスは占有されています。",975
"error.impassable": "そのマスは通行不能です。",976
"error.out_of_range": "そのプレイヤーは射程外です。",977
"error.invalid_move": "その行動はできません。",978
"error.game_started": "このゲームはすでに始まっています。",979
"error.game_finished": "このゲームは終了しています。",980
"error.lobby_full": "このロビーは満員です。",981
"error.unknown_code": "そのコードのロビーは見つかりません。",982
"error.cannot_vote": "今は投票できません。",983
"error.bad_vote": "生存中のプレイヤーにしか投票できません。",984
"error.bad_give": "そんなに多くの行動力は渡せません。",985
"error.unknown_action": "不明な行動です。",986
"error.ceasefire": "停戦時間中は攻撃できません。",987
"error.generic": "問題が発生しました。もう一度お試しください。",988
"error.serverStatus": "サーバーは{status}を返しました。"989
},990
"zh": {991
"app.name": "Allianties",992
"menu.tagline": "一场关于耐心、同盟与精准开火的游戏。",993
"menu.login": "登录",994
"menu.logout": "退出登录",995
"menu.loggedInAs": "已登录为",996
"menu.localTest": "本地测试:",997
"menu.create": "新建大厅",998
"menu.join": "加入",999
"menu.codePlaceholder": "代码",1000
"menu.myGames": "你的对局",1001
"menu.noGames": "你还没有任何对局。新建一个大厅并邀请其他人吧。",1002
"menu.authUnconfiguredHtml": "此服务器尚未设置登录。需要在 auth.timfalken.com 上注册回调 <code>/allianties/callback.php</code>,并配置客户端密钥。",1003
"menu.guestHint": "登录后可以创建大厅、邀请玩家并开始一局长时间进行的游戏。",1004
"menu.open": "打开",1005
"menu.continue": "继续",1006
"menu.statusLobby": "大厅",1007
"menu.statusRunning": "进行中",1008
"menu.statusFinished": "已结束",1009
"menu.youWon": "你赢了",1010
"menu.draw": "平局",1011
"menu.winnerIs": "胜者:{name}",1012
"menu.needLogin": "请先登录再游戏。",1013
"menu.players": "玩家",1014
"lobby.title": "大厅",1015
"lobby.invite": "邀请",1016
"lobby.copy": "复制链接",1017
"lobby.copied": "已复制",1018
"lobby.shareHint": "分享此代码或链接。玩家登录后即可加入。",1019
"lobby.players": "玩家",1020
"lobby.start": "开始游戏",1021
"lobby.leave": "离开大厅",1022
"lobby.host": "房主",1023
"lobby.you": "你",1024
"lobby.minPlayers": "至少需要两名玩家才能开始。",1025
"lobby.needTwo": "正在等待至少再来一名玩家…",1026
"lobby.rules": "规则",1027
"lobby.jury": "陪审团",1028
"lobby.juryHint": "被淘汰的玩家每天为一名仍存活的玩家投票。得票最多的玩家在下一次每日发放时额外获得 1 点行动点。若并列,所有并列者都获得奖励。投票对他人保密,并可在发放前更改。",1029
"lobby.shrink": "缩小的战场",1030
"lobby.shrinkHint": "每隔设定的天数,在每日发放时外圈会变为不可通行。站在上面的玩家失去 1 点生命并被推向内侧。",1031
"lobby.shrinkDays": "两次缩小间隔天数",1032
"lobby.shrinkDaysHint": "第一次缩小发生在这么多个午夜之后,之后每隔同样天数再缩小,直到战场达到最小尺寸。",1033
"lobby.ceasefire": "强制停火时段",1034
"lobby.ceasefireHint": "在这些时段(Europe/Amsterdam)任何人不得射击。移动、给予行动点和提升射程仍然允许。时段可以跨越午夜。",1035
"lobby.ceasefireAdd": "添加时段",1036
"lobby.ceasefireRemove": "删除",1037
"lobby.ceasefireStart": "从",1038
"lobby.ceasefireEnd": "至",1039
"lobby.ceasefireEmpty": "还没有时段。请添加一个,或在时钟上拖出一段扇形。",1040
"lobby.ceasefireClock": "24 小时时钟。拖动手柄或画出扇形;红色为停火,金色为可开火。时间为 Europe/Amsterdam。",1041
"lobby.apLoot": "击杀时夺取行动点",1042
"lobby.apLootHint": "用射击淘汰玩家时,你会获得其剩余行动点。投降和缩小场地不会转移点数。默认关闭。",1043
"lobby.apTime": "每日行动点发放时间",1044
"lobby.apTimeHint": "Europe/Amsterdam。行动点、陪审团奖励和场地缩小每天都在此时发生。默认 00:00。",1045
"lobby.visibility": "可见性",1046
"lobby.visibilityHint": "谁能看到什么。你始终能看到自己的生命、行动点和射程。移动始终公开。服务器会按观看者隐藏其余信息;被隐藏的事件完全不会出现在时间轴上。",1047
"lobby.visShots": "射击",1048
"lobby.visShotsPublic": "公开",1049
"lobby.visShotsElimPublic": "仅公开淘汰性射击",1050
"lobby.visShotsKnownTarget": "仅目标知晓",1051
"lobby.visShotsElimKnownTarget": "仅淘汰性射击为目标所知",1052
"lobby.visGifts": "赠予",1053
"lobby.visGiftsPublic": "公开",1054
"lobby.visGiftsKnownRecipient": "仅接收者知晓",1055
"lobby.visGiftsAnonymous": "匿名——接收者获得点数,但须自行推断来自谁",1056
"lobby.visAp": "行动点总数",1057
"lobby.visApPublic": "公开",1058
"lobby.visApHidden": "隐藏",1059
"lobby.visRange": "射程",1060
"lobby.visRangePublic": "公开",1061
"lobby.visRangeInRange": "射程内的玩家可知",1062
"lobby.visRangeHidden": "隐藏",1063
"lobby.visLives": "生命",1064
"lobby.visLivesPublic": "公开",1065
"lobby.visLivesHidden": "隐藏",1066
"info.hidden": "隐藏",1067
"lobby.waiting": "等待房主开始游戏。",1068
"lobby.back": "返回",1069
"lobby.code": "代码",1070
"lobby.playerCount.one": "{n} 名玩家",1071
"lobby.playerCount.other": "{n} 名玩家",1072
"lobby.playerCount.few": "{n} 名玩家",1073
"lobby.playerCount.many": "{n} 名玩家",1074
"game.day": "第 {n} 天",1075
"game.nextAp": "下次行动点",1076
"game.lives": "生命",1077
"game.ap": "行动点",1078
"game.range": "射程",1079
"game.you": "你",1080
"game.dead": "已淘汰",1081
"game.surrendered": "已投降",1082
"game.winner": "{name} 获胜!",1083
"game.youWin": "你赢了!",1084
"game.draw": "本局以平局结束。",1085
"game.shrinkIn": "战场将在 {n} 天后缩小",1086
"game.shrinkInDays.one": "战场将在 {n} 天后缩小",1087
"game.shrinkInDays.other": "战场将在 {n} 天后缩小",1088
"game.shrinkInDays.few": "战场将在 {n} 天后缩小",1089
"game.shrinkInDays.many": "战场将在 {n} 天后缩小",1090
"game.shrinkTomorrow": "战场将在明天缩小",1091
"game.shrinkToday": "战场将在下次发放时缩小",1092
"game.upgrade": "提升射程",1093
"game.settings": "设置",1094
"game.surrender": "投降",1095
"game.surrenderConfirm": "确定投降?你将退出本局,且无法撤销。",1096
"game.surrenderConfirmBtn": "是的,投降",1097
"game.surrenderCancel": "取消",1098
"game.back": "返回菜单",1099
"game.spectating": "你已被淘汰。你仍可观战、发送消息,并在陪审团开启时投票。",1100
"game.ceasefireLeft": "停火剩余时间",1101
"game.ceasefireUntil": "距离停火",1102
"game.ceasefireActive": "停火中",1103
"game.attackDisabled": "攻击",1104
"game.attackDisabledReason": "停火时段内不得攻击。",1105
"game.selectSelf": "已选中你的坦克。点按高亮格子移动,或提升射程。",1106
"game.impassable": "不可通行",1107
"game.willShrink": "下一圈将缩小",1108
"opt.info": "信息",1109
"opt.attack": "攻击",1110
"opt.give": "给予行动点",1111
"opt.message": "发送消息",1112
"opt.close": "关闭",1113
"info.title": "信息",1114
"info.lives": "生命",1115
"info.ap": "行动点",1116
"info.range": "射程",1117
"info.notes": "你的私人备注",1118
"info.notesHint": "只有你能看到这些备注。它们保存在你的账户中。",1119
"info.saveNotes": "保存备注",1120
"info.saved": "已保存",1121
"give.title": "给予行动点",1122
"give.howMany": "给多少?",1123
"give.send": "给予",1124
"give.youHave": "你有 {n} 点。",1125
"chat.title": "给 {name} 的消息",1126
"chat.placeholder": "写一条私人消息…",1127
"chat.send": "发送",1128
"chat.empty": "还没有消息。",1129
"jury.title": "陪审团",1130
"jury.hint": "为一名仍存活的玩家投票。得票最多者在下次发放时额外获得 1 点行动点。在此之前可以改票。其他玩家看不到你的投票。",1131
"jury.vote": "投票",1132
"jury.votedFor": "你把票投给了 {name}",1133
"jury.change": "改票",1134
"timeline.play": "播放",1135
"timeline.pause": "暂停",1136
"timeline.live": "实时",1137
"timeline.stepBack": "后退一步",1138
"timeline.stepForward": "前进一步",1139
"timeline.event.start": "游戏开始",1140
"timeline.event.move": "{name} 移动了",1141
"timeline.event.shoot": "{name} 向 {target} 射击",1142
"timeline.event.give": "{name} 将 {n} 点行动点给了 {target}",1143
"timeline.event.upgrade": "{name} 将射程提升到 {n}",1144
"timeline.event.surrender": "{name} 投降了",1145
"timeline.event.daily": "第 {n} 天:发放行动点",1146
"timeline.event.jury": "陪审团将奖励发给 {name}",1147
"timeline.event.juryTie": "陪审团将奖励发给 {names}",1148
"timeline.event.shrink": "战场缩小了",1149
"timeline.event.win": "{name} 获胜",1150
"timeline.event.death": "{name} 被淘汰",1151
"timeline.event.deathShot": "{name} 被 {by} 击倒",1152
"timeline.event.deathShrink": "{name} 被缩小的战场波及",1153
"timeline.event.deathCrushed": "{name} 被挤出:没有空余格子",1154
"timeline.event.draw": "本局以平局结束",1155
"auth.unavailable": "登录暂时不可用。",1156
"auth.backToGame": "返回 Allianties",1157
"auth.failed": "登录失败。",1158
"auth.retry": "重试",1159
"auth.back": "返回",1160
"lang.choose": "选择语言",1161
"lang.current": "语言:{name}",1162
"error.login": "请登录后再继续。",1163
"error.csrf": "会话已过期。请刷新页面后再试。",1164
"error.not_host": "只有房主可以这样做。",1165
"error.min_players": "至少需要两名玩家才能开始。",1166
"error.not_in_game": "你不在这局游戏中。",1167
"error.dead": "你已从本局淘汰。",1168
"error.no_ap": "你没有剩余的行动点。",1169
"error.occupied": "该格子已被占用。",1170
"error.impassable": "该格子不可通行。",1171
"error.out_of_range": "该玩家超出射程。",1172
"error.invalid_move": "不允许这样行动。",1173
"error.game_started": "这局游戏已经开始。",1174
"error.game_finished": "这局游戏已经结束。",1175
"error.lobby_full": "此大厅已满。",1176
"error.unknown_code": "找不到该代码对应的大厅。",1177
"error.cannot_vote": "你现在不能投票。",1178
"error.bad_vote": "只能为仍存活的玩家投票。",1179
"error.bad_give": "不能给予那么多行动点。",1180
"error.unknown_action": "未知操作。",1181
"error.ceasefire": "停火时段内不能攻击。",1182
"error.generic": "出了点问题,请再试一次。",1183
"error.serverStatus": "服务器返回了 {status}。"1184
},1185
"ko": {1186
"app.name": "Allianties",1187
"menu.tagline": "인내와 동맹, 그리고 때를 놓치지 않는 사격의 게임.",1188
"menu.login": "로그인",1189
"menu.logout": "로그아웃",1190
"menu.loggedInAs": "로그인됨",1191
"menu.localTest": "로컬 테스트:",1192
"menu.create": "새 로비",1193
"menu.join": "참가",1194
"menu.codePlaceholder": "코드",1195
"menu.myGames": "내 게임",1196
"menu.noGames": "아직 게임이 없습니다. 로비를 만들고 다른 사람을 초대하세요.",1197
"menu.authUnconfiguredHtml": "이 서버에는 아직 로그인이 설정되지 않았습니다. 콜백 <code>/allianties/callback.php</code>를 auth.timfalken.com에 등록하고 클라이언트 비밀키를 설정해야 합니다.",1198
"menu.guestHint": "로그인하면 로비를 만들고, 플레이어를 초대하고, 오래 이어지는 게임을 시작할 수 있습니다.",1199
"menu.open": "열기",1200
"menu.continue": "계속",1201
"menu.statusLobby": "로비",1202
"menu.statusRunning": "진행 중",1203
"menu.statusFinished": "종료",1204
"menu.youWon": "승리",1205
"menu.draw": "무승부",1206
"menu.winnerIs": "승자: {name}",1207
"menu.needLogin": "플레이하려면 먼저 로그인하세요.",1208
"menu.players": "플레이어",1209
"lobby.title": "로비",1210
"lobby.invite": "초대",1211
"lobby.copy": "링크 복사",1212
"lobby.copied": "복사됨",1213
"lobby.shareHint": "이 코드나 링크를 공유하세요. 플레이어는 로그인한 뒤 참가합니다.",1214
"lobby.players": "플레이어",1215
"lobby.start": "게임 시작",1216
"lobby.leave": "로비 나가기",1217
"lobby.host": "호스트",1218
"lobby.you": "나",1219
"lobby.minPlayers": "시작하려면 플레이어가 최소 두 명 필요합니다.",1220
"lobby.needTwo": "플레이어를 최소 한 명 더 기다리는 중…",1221
"lobby.rules": "규칙",1222
"lobby.jury": "배심",1223
"lobby.juryHint": "탈락한 플레이어는 매일 생존 중인 플레이어 한 명에게 투표합니다. 가장 많은 표를 받은 플레이어는 다음 일일 지급 때 행동력을 하나 더 받습니다. 동점이면 동점인 전원에게 보너스가 갑니다. 표는 비밀이며 지급 전까지 바꿀 수 있습니다.",1224
"lobby.shrink": "줄어드는 전장",1225
"lobby.shrinkHint": "설정한 일수가 지나면 일일 지급 때 바깥 고리가 통과 불가가 됩니다. 그 위에 있는 플레이어는 목숨을 하나 잃고 안쪽으로 밀립니다.",1226
"lobby.shrinkDays": "축소 간격(일)",1227
"lobby.shrinkDaysHint": "첫 축소는 그 횟수만큼의 자정이 지난 뒤, 이후 같은 일수마다 반복되며 전장이 최소 크기에 이를 때까지 계속됩니다.",1228
"lobby.ceasefire": "강제 휴전 시간",1229
"lobby.ceasefireHint": "이 시간대(Europe/Amsterdam)에는 아무도 발사할 수 없습니다. 이동, 행동력 전달, 사거리 강화는 가능합니다. 구간은 자정을 넘길 수 있습니다.",1230
"lobby.ceasefireAdd": "구간 추가",1231
"lobby.ceasefireRemove": "삭제",1232
"lobby.ceasefireStart": "시작",1233
"lobby.ceasefireEnd": "종료",1234
"lobby.ceasefireEmpty": "아직 구간이 없습니다. 하나를 추가하거나 시계에서 부채꼴을 드래그하세요.",1235
"lobby.ceasefireClock": "24시간 시계. 핸들을 드래그하거나 부채꼴을 그리세요. 빨강은 휴전, 금색은 사격 가능. 시각은 Europe/Amsterdam입니다.",1236
"lobby.apLoot": "처치 시 행동력 탈취",1237
"lobby.apLootHint": "사격으로 플레이어를 처치하면 남은 행동력을 받습니다. 항복과 축소되는 전장에서는 이전되지 않습니다. 기본값은 꺼짐입니다.",1238
"lobby.apTime": "매일 행동력 지급 시각",1239
"lobby.apTimeHint": "Europe/Amsterdam. 행동력, 배심 보너스, 전장 축소가 매일 이 시각에 일어납니다. 기본값은 00:00입니다.",1240
"lobby.visibility": "공개 범위",1241
"lobby.visibilityHint": "누가 무엇을 볼 수 있는지. 자신의 생명, 행동력, 사거리는 항상 보입니다. 이동은 항상 공개됩니다. 서버가 보는 사람마다 나머지를 숨기며, 숨겨진 사건은 타임라인에 전혀 나타나지 않습니다.",1242
"lobby.visShots": "사격",1243
"lobby.visShotsPublic": "공개",1244
"lobby.visShotsElimPublic": "처치하는 사격만 공개",1245
"lobby.visShotsKnownTarget": "대상만 알 수 있음",1246
"lobby.visShotsElimKnownTarget": "대상은 처치하는 사격만 알 수 있음",1247
"lobby.visGifts": "선물",1248
"lobby.visGiftsPublic": "공개",1249
"lobby.visGiftsKnownRecipient": "받는 사람만 알 수 있음",1250
"lobby.visGiftsAnonymous": "익명 — 받는 사람은 점수를 얻지만 누가 줬는지는 스스로 추론해야 함",1251
"lobby.visAp": "행동력 합계",1252
"lobby.visApPublic": "공개",1253
"lobby.visApHidden": "숨김",1254
"lobby.visRange": "사거리",1255
"lobby.visRangePublic": "공개",1256
"lobby.visRangeInRange": "사거리 안의 플레이어에게 알려짐",1257
"lobby.visRangeHidden": "숨김",1258
"lobby.visLives": "생명",1259
"lobby.visLivesPublic": "공개",1260
"lobby.visLivesHidden": "숨김",1261
"info.hidden": "숨김",1262
"lobby.waiting": "호스트가 게임을 시작하기를 기다리는 중.",1263
"lobby.back": "뒤로",1264
"lobby.code": "코드",1265
"lobby.playerCount.one": "플레이어 {n}명",1266
"lobby.playerCount.other": "플레이어 {n}명",1267
"lobby.playerCount.few": "플레이어 {n}명",1268
"lobby.playerCount.many": "플레이어 {n}명",1269
"game.day": "{n}일차",1270
"game.nextAp": "다음 행동력",1271
"game.lives": "목숨",1272
"game.ap": "행동력",1273
"game.range": "사거리",1274
"game.you": "나",1275
"game.dead": "탈락",1276
"game.surrendered": "항복함",1277
"game.winner": "{name} 승리!",1278
"game.youWin": "당신이 이겼습니다!",1279
"game.draw": "게임이 무승부로 끝났습니다.",1280
"game.shrinkIn": "전장이 {n}일 후 줄어듭니다",1281
"game.shrinkInDays.one": "전장이 {n}일 후 줄어듭니다",1282
"game.shrinkInDays.other": "전장이 {n}일 후 줄어듭니다",1283
"game.shrinkInDays.few": "전장이 {n}일 후 줄어듭니다",1284
"game.shrinkInDays.many": "전장이 {n}일 후 줄어듭니다",1285
"game.shrinkTomorrow": "전장이 내일 줄어듭니다",1286
"game.shrinkToday": "전장이 다음 지급 때 줄어듭니다",1287
"game.upgrade": "사거리 강화",1288
"game.settings": "설정",1289
"game.surrender": "항복",1290
"game.surrenderConfirm": "항복할까요? 이 게임에서 탈락하며 되돌릴 수 없습니다.",1291
"game.surrenderConfirmBtn": "네, 항복합니다",1292
"game.surrenderCancel": "취소",1293
"game.back": "메뉴로 돌아가기",1294
"game.spectating": "탈락했습니다. 관전, 메시지 보내기, 배심이 켜져 있다면 투표는 계속할 수 있습니다.",1295
"game.ceasefireLeft": "휴전 남은 시간",1296
"game.ceasefireUntil": "휴전까지",1297
"game.ceasefireActive": "휴전 중",1298
"game.attackDisabled": "공격",1299
"game.attackDisabledReason": "휴전 시간에는 공격할 수 없습니다.",1300
"game.selectSelf": "내 전차가 선택되었습니다. 강조된 칸을 눌러 이동하거나 사거리를 강화하세요.",1301
"game.impassable": "통과 불가",1302
"game.willShrink": "다음에 줄어들 고리",1303
"opt.info": "정보",1304
"opt.attack": "공격",1305
"opt.give": "행동력 주기",1306
"opt.message": "메시지 보내기",1307
"opt.close": "닫기",1308
"info.title": "정보",1309
"info.lives": "목숨",1310
"info.ap": "행동력",1311
"info.range": "사거리",1312
"info.notes": "나만 보는 메모",1313
"info.notesHint": "이 메모는 당신만 볼 수 있습니다. 계정에 저장됩니다.",1314
"info.saveNotes": "메모 저장",1315
"info.saved": "저장됨",1316
"give.title": "행동력 주기",1317
"give.howMany": "몇 개?",1318
"give.send": "주기",1319
"give.youHave": "{n}개를 가지고 있습니다.",1320
"chat.title": "{name}에게 메시지",1321
"chat.placeholder": "비공개 메시지를 작성하세요…",1322
"chat.send": "보내기",1323
"chat.empty": "아직 메시지가 없습니다.",1324
"jury.title": "배심",1325
"jury.hint": "생존 중인 플레이어 한 명에게 투표하세요. 가장 많은 표를 받은 사람은 다음 지급 때 행동력을 하나 더 받습니다. 그 전까지 표를 바꿀 수 있습니다. 다른 플레이어는 당신의 표를 볼 수 없습니다.",1326
"jury.vote": "투표",1327
"jury.votedFor": "{name}에게 투표했습니다",1328
"jury.change": "투표 변경",1329
"timeline.play": "재생",1330
"timeline.pause": "일시정지",1331
"timeline.live": "실시간",1332
"timeline.stepBack": "한 단계 뒤로",1333
"timeline.stepForward": "한 단계 앞으로",1334
"timeline.event.start": "게임이 시작됩니다",1335
"timeline.event.move": "{name}이(가) 이동합니다",1336
"timeline.event.shoot": "{name}이(가) {target}을(를) 공격합니다",1337
"timeline.event.give": "{name}이(가) {target}에게 행동력 {n}개를 줍니다",1338
"timeline.event.upgrade": "{name}이(가) 사거리를 {n}(으)로 올립니다",1339
"timeline.event.surrender": "{name}이(가) 항복합니다",1340
"timeline.event.daily": "{n}일차: 행동력 지급",1341
"timeline.event.jury": "배심이 {name}에게 보너스를 줍니다",1342
"timeline.event.juryTie": "배심이 {names}에게 보너스를 줍니다",1343
"timeline.event.shrink": "전장이 줄어듭니다",1344
"timeline.event.win": "{name} 승리",1345
"timeline.event.death": "{name} 탈락",1346
"timeline.event.deathShot": "{name}이(가) {by}에게 피격되어 탈락",1347
"timeline.event.deathShrink": "{name}이(가) 줄어드는 전장에 걸렸습니다",1348
"timeline.event.deathCrushed": "{name}이(가) 깔렸습니다: 빈 칸이 없습니다",1349
"timeline.event.draw": "게임이 무승부로 끝납니다",1350
"auth.unavailable": "로그인을 잠시 사용할 수 없습니다.",1351
"auth.backToGame": "Allianties로 돌아가기",1352
"auth.failed": "로그인에 실패했습니다.",1353
"auth.retry": "다시 시도",1354
"auth.back": "뒤로",1355
"lang.choose": "언어 선택",1356
"lang.current": "언어: {name}",1357
"error.login": "계속하려면 로그인하세요.",1358
"error.csrf": "세션이 만료되었습니다. 페이지를 새로 고친 뒤 다시 시도하세요.",1359
"error.not_host": "호스트만 할 수 있습니다.",1360
"error.min_players": "시작하려면 플레이어가 최소 두 명 필요합니다.",1361
"error.not_in_game": "이 게임에 들어가 있지 않습니다.",1362
"error.dead": "이 게임에서 탈락했습니다.",1363
"error.no_ap": "남은 행동력이 없습니다.",1364
"error.occupied": "그 칸은 이미 차지되어 있습니다.",1365
"error.impassable": "그 칸은 통과할 수 없습니다.",1366
"error.out_of_range": "그 플레이어는 사거리 밖입니다.",1367
"error.invalid_move": "그 행동은 허용되지 않습니다.",1368
"error.game_started": "이 게임은 이미 시작되었습니다.",1369
"error.game_finished": "이 게임은 이미 끝났습니다.",1370
"error.lobby_full": "이 로비는 가득 찼습니다.",1371
"error.unknown_code": "그 코드의 로비를 찾을 수 없습니다.",1372
"error.cannot_vote": "지금은 투표할 수 없습니다.",1373
"error.bad_vote": "생존 중인 플레이어에게만 투표할 수 있습니다.",1374
"error.bad_give": "그만큼의 행동력은 줄 수 없습니다.",1375
"error.unknown_action": "알 수 없는 행동입니다.",1376
"error.ceasefire": "휴전 시간에는 공격할 수 없습니다.",1377
"error.generic": "문제가 발생했습니다. 다시 시도해 주세요.",1378
"error.serverStatus": "서버가 {status}을(를) 반환했습니다."1379
},1380
"pl": {1381
"app.name": "Allianties",1382
"menu.tagline": "Gra cierpliwości, sojuszy i dobrze wycelowanych strzałów.",1383
"menu.login": "Zaloguj się",1384
"menu.logout": "Wyloguj się",1385
"menu.loggedInAs": "Zalogowano jako",1386
"menu.localTest": "test lokalny:",1387
"menu.create": "Nowe lobby",1388
"menu.join": "Dołącz",1389
"menu.codePlaceholder": "Kod",1390
"menu.myGames": "Twoje gry",1391
"menu.noGames": "Nie masz jeszcze żadnych gier. Załóż lobby i zaproś innych.",1392
"menu.authUnconfiguredHtml": "Logowanie nie jest jeszcze skonfigurowane na tym serwerze. Callback <code>/allianties/callback.php</code> musi zostać zarejestrowany w auth.timfalken.com, a sekret klienta musi zostać ustawiony.",1393
"menu.guestHint": "Zaloguj się, aby utworzyć lobby, zaprosić graczy i rozpocząć trwałą rozgrywkę.",1394
"menu.open": "Otwórz",1395
"menu.continue": "Kontynuuj",1396
"menu.statusLobby": "Lobby",1397
"menu.statusRunning": "W toku",1398
"menu.statusFinished": "Zakończona",1399
"menu.youWon": "Wygrana",1400
"menu.draw": "Remis",1401
"menu.winnerIs": "Zwycięzca: {name}",1402
"menu.needLogin": "Najpierw zaloguj się, aby zagrać.",1403
"menu.players": "Gracze",1404
"lobby.title": "Lobby",1405
"lobby.invite": "Zaproś",1406
"lobby.copy": "Kopiuj link",1407
"lobby.copied": "Skopiowano",1408
"lobby.shareHint": "Udostępnij ten kod lub link. Gracze logują się i dołączają.",1409
"lobby.players": "Gracze",1410
"lobby.start": "Rozpocznij grę",1411
"lobby.leave": "Opuść lobby",1412
"lobby.host": "Gospodarz",1413
"lobby.you": "ty",1414
"lobby.minPlayers": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",1415
"lobby.needTwo": "Oczekiwanie na co najmniej jednego gracza…",1416
"lobby.rules": "Zasady",1417
"lobby.jury": "Jury",1418
"lobby.juryHint": "Eliminowani gracze codziennie głosują na żywego gracza. Osoba z największą liczbą głosów otrzymuje dodatkowy punkt akcji przy kolejnym codziennym rozdaniu. Przy remisie bonus dostaje każdy z ex aequo. Głosy są tajne i można je zmieniać do tego momentu.",1419
"lobby.shrink": "Kurcząca się arena",1420
"lobby.shrinkHint": "Po ustalonej liczbie dni zewnętrzny pierścień staje się nieprzekraczalny przy codziennym rozdaniu. Gracze, którzy na nim stoją, tracą jedno życie i są spychani do środka.",1421
"lobby.shrinkDays": "Dni między skurczeniami",1422
"lobby.shrinkDaysHint": "Pierwsze skurczenie po tylu północach, potem ponownie co tyle samo dni, aż arena osiągnie minimalny rozmiar.",1423
"lobby.ceasefire": "Wymuszone godziny zawieszenia broni",1424
"lobby.ceasefireHint": "W tych godzinach (Europe/Amsterdam) nikt nie może strzelać. Ruch, przekazywanie punktów akcji i zwiększanie zasięgu pozostają dozwolone. Zakresy mogą przekraczać północ.",1425
"lobby.ceasefireAdd": "Dodaj okres",1426
"lobby.ceasefireRemove": "Usuń",1427
"lobby.ceasefireStart": "Od",1428
"lobby.ceasefireEnd": "Do",1429
"lobby.ceasefireEmpty": "Brak okresów. Dodaj jeden albo narysuj wycinek na zegarze.",1430
"lobby.ceasefireClock": "Zegar 24-godzinny. Przeciągaj uchwyty lub maluj wycinek; czerwień to zawieszenie broni, złoto to dowolność strzału. Czas: Europe/Amsterdam.",1431
"lobby.apLoot": "Przejmowanie punktów akcji przy eliminacji",1432
"lobby.apLootHint": "Gdy wyeliminujesz gracza strzałem, otrzymujesz jego pozostałe punkty akcji. Poddanie się i kurczenie areny nie przekazują punktów. Domyślnie wyłączone.",1433
"lobby.apTime": "Codzienne punkty akcji o",1434
"lobby.apTimeHint": "Europe/Amsterdam. Punkty akcji, nagrody jury i kurczenie areny odbywają się codziennie o tej godzinie. Domyślnie 00:00.",1435
"lobby.visibility": "Widoczność",1436
"lobby.visibilityHint": "Kto co widzi. Zawsze widzisz własne życia, punkty akcji i zasięg. Ruchy są zawsze publiczne. Serwer ukrywa resztę przed każdym widzem; ukryte zdarzenia w ogóle nie pojawiają się na osi czasu.",1437
"lobby.visShots": "Strzały",1438
"lobby.visShotsPublic": "Publiczne",1439
"lobby.visShotsElimPublic": "Publiczne są tylko strzały eliminujące",1440
"lobby.visShotsKnownTarget": "Znane tylko celowi",1441
"lobby.visShotsElimKnownTarget": "Cel zna tylko strzał eliminujący",1442
"lobby.visGifts": "Dary",1443
"lobby.visGiftsPublic": "Publiczne",1444
"lobby.visGiftsKnownRecipient": "Znane tylko odbiorcy",1445
"lobby.visGiftsAnonymous": "Anonimowo — odbiorca dostaje punkty, ale musi sam wywnioskować, od kogo",1446
"lobby.visAp": "Sumy punktów akcji",1447
"lobby.visApPublic": "Publiczne",1448
"lobby.visApHidden": "Ukryte",1449
"lobby.visRange": "Zasięg",1450
"lobby.visRangePublic": "Publiczne",1451
"lobby.visRangeInRange": "Znane graczom w zasięgu",1452
"lobby.visRangeHidden": "Ukryte",1453
"lobby.visLives": "Życia",1454
"lobby.visLivesPublic": "Publiczne",1455
"lobby.visLivesHidden": "Ukryte",1456
"info.hidden": "Ukryte",1457
"lobby.waiting": "Czekamy, aż gospodarz rozpocznie grę.",1458
"lobby.back": "Wstecz",1459
"lobby.code": "Kod",1460
"lobby.playerCount.one": "{n} gracz",1461
"lobby.playerCount.other": "{n} graczy",1462
"lobby.playerCount.few": "{n} graczy",1463
"lobby.playerCount.many": "{n} graczy",1464
"game.day": "Dzień {n}",1465
"game.nextAp": "Następne punkty akcji",1466
"game.lives": "Życia",1467
"game.ap": "Punkty akcji",1468
"game.range": "Zasięg",1469
"game.you": "Ty",1470
"game.dead": "Eliminacja",1471
"game.surrendered": "Poddał się",1472
"game.winner": "{name} wygrywa!",1473
"game.youWin": "Wygrywasz!",1474
"game.draw": "Gra kończy się remisem.",1475
"game.shrinkIn": "Arena skurczy się za {n} dni",1476
"game.shrinkInDays.one": "Arena skurczy się za {n} dzień",1477
"game.shrinkInDays.other": "Arena skurczy się za {n} dni",1478
"game.shrinkInDays.few": "Arena skurczy się za {n} dni",1479
"game.shrinkInDays.many": "Arena skurczy się za {n} dni",1480
"game.shrinkTomorrow": "Arena skurczy się jutro",1481
"game.shrinkToday": "Arena skurczy się przy następnym rozdaniu",1482
"game.upgrade": "Zwiększ zasięg",1483
"game.settings": "Ustawienia",1484
"game.surrender": "Poddaj się",1485
"game.surrenderConfirm": "Poddać się? Odpadniesz z tej gry. Tej czynności nie można cofnąć.",1486
"game.surrenderConfirmBtn": "Tak, poddaję się",1487
"game.surrenderCancel": "Anuluj",1488
"game.back": "Powrót do menu",1489
"game.spectating": "Odpadłeś. Nadal możesz oglądać, wysyłać wiadomości i — jeśli jury jest włączone — głosować.",1490
"game.ceasefireLeft": "Pozostały czas zawieszenia broni",1491
"game.ceasefireUntil": "Czas do zawieszenia broni",1492
"game.ceasefireActive": "Zawieszenie broni",1493
"game.attackDisabled": "Atak",1494
"game.attackDisabledReason": "Atak jest niedozwolony w godzinach zawieszenia broni.",1495
"game.selectSelf": "Twój czołg jest zaznaczony. Dotknij podświetlonego pola, aby się ruszyć, albo zwiększ zasięg.",1496
"game.impassable": "Nieprzekraczalne",1497
"game.willShrink": "Ten pierścień skurczy się jako następny",1498
"opt.info": "Informacje",1499
"opt.attack": "Atakuj",1500
"opt.give": "Przekaż punkty akcji",1501
"opt.message": "Wyślij wiadomość",1502
"opt.close": "Zamknij",1503
"info.title": "Informacje",1504
"info.lives": "Życia",1505
"info.ap": "Punkty akcji",1506
"info.range": "Zasięg",1507
"info.notes": "Twoje prywatne notatki",1508
"info.notesHint": "Tylko ty widzisz te notatki. Są przechowywane przy twoim koncie.",1509
"info.saveNotes": "Zapisz notatki",1510
"info.saved": "Zapisano",1511
"give.title": "Przekaż punkty akcji",1512
"give.howMany": "Ile?",1513
"give.send": "Przekaż",1514
"give.youHave": "Masz {n}.",1515
"chat.title": "Wiadomość do {name}",1516
"chat.placeholder": "Napisz prywatną wiadomość…",1517
"chat.send": "Wyślij",1518
"chat.empty": "Nie ma jeszcze wiadomości.",1519
"jury.title": "Jury",1520
"jury.hint": "Zagłosuj na jednego żywego gracza. Osoba z największą liczbą głosów otrzyma dodatkowy punkt akcji przy następnym rozdaniu. Do tego czasu możesz zmienić głos. Inni gracze go nie widzą.",1521
"jury.vote": "Głosuj",1522
"jury.votedFor": "Zagłosowałeś na {name}",1523
"jury.change": "Zmień głos",1524
"timeline.play": "Odtwórz",1525
"timeline.pause": "Pauza",1526
"timeline.live": "Na żywo",1527
"timeline.stepBack": "Krok wstecz",1528
"timeline.stepForward": "Krok naprzód",1529
"timeline.event.start": "Gra się zaczyna",1530
"timeline.event.move": "{name} się przemieszcza",1531
"timeline.event.shoot": "{name} strzela do {target}",1532
"timeline.event.give": "{name} przekazuje {n} pkt. akcji dla {target}",1533
"timeline.event.upgrade": "{name} zwiększa zasięg do {n}",1534
"timeline.event.surrender": "{name} się poddaje",1535
"timeline.event.daily": "Dzień {n}: rozdanie punktów akcji",1536
"timeline.event.jury": "Jury przyznaje bonus dla {name}",1537
"timeline.event.juryTie": "Jury przyznaje bonus dla {names}",1538
"timeline.event.shrink": "Arena się kurczy",1539
"timeline.event.win": "{name} wygrywa",1540
"timeline.event.death": "{name} odpada",1541
"timeline.event.deathShot": "{name} zostaje zestrzelony przez {by}",1542
"timeline.event.deathShrink": "{name} zostaje złapany przez kurczącą się arenę",1543
"timeline.event.deathCrushed": "{name} zostaje zmiażdżony: nie ma wolnego pola",1544
"timeline.event.draw": "Gra kończy się remisem",1545
"auth.unavailable": "Logowanie jest chwilowo niedostępne.",1546
"auth.backToGame": "Powrót do Allianties",1547
"auth.failed": "Logowanie nie powiodło się.",1548
"auth.retry": "Spróbuj ponownie",1549
"auth.back": "Wstecz",1550
"lang.choose": "Wybierz język",1551
"lang.current": "Język: {name}",1552
"error.login": "Zaloguj się, aby kontynuować.",1553
"error.csrf": "Twoja sesja wygasła. Odśwież stronę i spróbuj ponownie.",1554
"error.not_host": "Tylko gospodarz może to zrobić.",1555
"error.min_players": "Do rozpoczęcia potrzeba co najmniej dwóch graczy.",1556
"error.not_in_game": "Nie jesteś w tej grze.",1557
"error.dead": "Odpadłeś z tej gry.",1558
"error.no_ap": "Nie masz już punktów akcji.",1559
"error.occupied": "To pole jest zajęte.",1560
"error.impassable": "To pole jest nieprzekraczalne.",1561
"error.out_of_range": "Ten gracz jest poza zasięgiem.",1562
"error.invalid_move": "Ten ruch jest niedozwolony.",1563
"error.game_started": "Ta gra już się rozpoczęła.",1564
"error.game_finished": "Ta gra się zakończyła.",1565
"error.lobby_full": "To lobby jest pełne.",1566
"error.unknown_code": "Nie znaleziono lobby o takim kodzie.",1567
"error.cannot_vote": "Teraz nie możesz głosować.",1568
"error.bad_vote": "Możesz głosować tylko na żywego gracza.",1569
"error.bad_give": "Nie możesz przekazać tylu punktów akcji.",1570
"error.unknown_action": "Nieznana akcja.",1571
"error.ceasefire": "Nie możesz atakować w godzinach zawieszenia broni.",1572
"error.generic": "Coś poszło nie tak. Spróbuj ponownie.",1573
"error.serverStatus": "Serwer zwrócił {status}."1574
},1575
"ru": {1576
"app.name": "Allianties",1577
"menu.tagline": "Игра в терпение, союзы и хорошо рассчитанные выстрелы.",1578
"menu.login": "Войти",1579
"menu.logout": "Выйти",1580
"menu.loggedInAs": "Вы вошли как",1581
"menu.localTest": "локальный тест:",1582
"menu.create": "Новое лобби",1583
"menu.join": "Присоединиться",1584
"menu.codePlaceholder": "Код",1585
"menu.myGames": "Ваши игры",1586
"menu.noGames": "У вас пока нет игр. Создайте лобби и пригласите других.",1587
"menu.authUnconfiguredHtml": "Вход на этом сервере ещё не настроен. Callback <code>/allianties/callback.php</code> нужно зарегистрировать на auth.timfalken.com, а секрет клиента — задать.",1588
"menu.guestHint": "Войдите, чтобы создать лобби, пригласить игроков и начать долгую партию.",1589
"menu.open": "Открыть",1590
"menu.continue": "Продолжить",1591
"menu.statusLobby": "Лобби",1592
"menu.statusRunning": "Идёт игра",1593
"menu.statusFinished": "Завершена",1594
"menu.youWon": "Вы победили",1595
"menu.draw": "Ничья",1596
"menu.winnerIs": "Победитель: {name}",1597
"menu.needLogin": "Сначала войдите, чтобы играть.",1598
"menu.players": "Игроки",1599
"lobby.title": "Лобби",1600
"lobby.invite": "Пригласить",1601
"lobby.copy": "Копировать ссылку",1602
"lobby.copied": "Скопировано",1603
"lobby.shareHint": "Поделитесь этим кодом или ссылкой. Игроки входят в аккаунт и присоединяются.",1604
"lobby.players": "Игроки",1605
"lobby.start": "Начать игру",1606
"lobby.leave": "Покинуть лобби",1607
"lobby.host": "Хозяин",1608
"lobby.you": "вы",1609
"lobby.minPlayers": "Для начала нужно как минимум два игрока.",1610
"lobby.needTwo": "Ждём ещё хотя бы одного игрока…",1611
"lobby.rules": "Правила",1612
"lobby.jury": "Жюри",1613
"lobby.juryHint": "Выбывшие игроки каждый день голосуют за живого игрока. Набравший больше всех голосов получает дополнительное очко действия при следующем ежедневном начислении. При ничьей бонус получают все, кто набрал одинаково максимум. Голоса тайные и их можно менять до начисления.",1614
"lobby.shrink": "Сжимающаяся арена",1615
"lobby.shrinkHint": "Через заданное число дней внешнее кольцо становится непроходимым в момент ежедневного начисления. Игроки, стоящие на нём, теряют одну жизнь и сдвигаются внутрь.",1616
"lobby.shrinkDays": "Дней между сжатиями",1617
"lobby.shrinkDaysHint": "Первое сжатие после стольких полуночей, затем снова через столько же дней, пока арена не достигнет минимального размера.",1618
"lobby.ceasefire": "Принудительное перемирие",1619
"lobby.ceasefireHint": "В эти часы (Europe/Amsterdam) стрелять нельзя. Ходить, передавать очки действия и увеличивать дальность по-прежнему можно. Интервалы могут переходить через полночь.",1620
"lobby.ceasefireAdd": "Добавить период",1621
"lobby.ceasefireRemove": "Удалить",1622
"lobby.ceasefireStart": "С",1623
"lobby.ceasefireEnd": "До",1624
"lobby.ceasefireEmpty": "Периодов пока нет. Добавьте один или нарисуйте сектор на часах.",1625
"lobby.ceasefireClock": "24-часовые часы. Перетаскивайте ручки или рисуйте сектор; красный — перемирие, золотой — огонь разрешён. Время: Europe/Amsterdam.",1626
"lobby.apLoot": "Забирать очки действий при убийстве",1627
"lobby.apLootHint": "Если вы устраняете игрока выстрелом, вы получаете его оставшиеся очки действий. Сдача и сужение арены очки не передают. По умолчанию выключено.",1628
"lobby.apTime": "Ежедневные очки действий в",1629
"lobby.apTimeHint": "Europe/Amsterdam. Очки действий, бонусы жюри и сужение арены происходят каждый день в это время. По умолчанию 00:00.",1630
"lobby.visibility": "Видимость",1631
"lobby.visibilityHint": "Кто что видит. Вы всегда видите свои жизни, очки действий и дальность. Перемещение всегда открыто. Сервер скрывает всё остальное для каждого зрителя; скрытые события вообще не появляются на шкале времени.",1632
"lobby.visShots": "Выстрелы",1633
"lobby.visShotsPublic": "Открыто",1634
"lobby.visShotsElimPublic": "Открыты только устраняющие выстрелы",1635
"lobby.visShotsKnownTarget": "Известно только цели",1636
"lobby.visShotsElimKnownTarget": "Цели известен только устраняющий выстрел",1637
"lobby.visGifts": "Подарки",1638
"lobby.visGiftsPublic": "Открыто",1639
"lobby.visGiftsKnownRecipient": "Известно только получателю",1640
"lobby.visGiftsAnonymous": "Анонимно — получатель получает очки, но должен сам догадаться, от кого",1641
"lobby.visAp": "Запасы очков действий",1642
"lobby.visApPublic": "Открыто",1643
"lobby.visApHidden": "Скрыто",1644
"lobby.visRange": "Дальность",1645
"lobby.visRangePublic": "Открыто",1646
"lobby.visRangeInRange": "Известно игрокам в пределах дальности",1647
"lobby.visRangeHidden": "Скрыто",1648
"lobby.visLives": "Жизни",1649
"lobby.visLivesPublic": "Открыто",1650
"lobby.visLivesHidden": "Скрыто",1651
"info.hidden": "Скрыто",1652
"lobby.waiting": "Ждём, пока хозяин начнёт игру.",1653
"lobby.back": "Назад",1654
"lobby.code": "Код",1655
"lobby.playerCount.one": "{n} игрок",1656
"lobby.playerCount.other": "{n} игроков",1657
"lobby.playerCount.few": "{n} игрока",1658
"lobby.playerCount.many": "{n} игроков",1659
"game.day": "День {n}",1660
"game.nextAp": "Следующие очки действия",1661
"game.lives": "Жизни",1662
"game.ap": "Очки действия",1663
"game.range": "Дальность",1664
"game.you": "Вы",1665
"game.dead": "Выбыл",1666
"game.surrendered": "Сдался",1667
"game.winner": "{name} побеждает!",1668
"game.youWin": "Вы победили!",1669
"game.draw": "Игра заканчивается вничью.",1670
"game.shrinkIn": "Арена сожмётся через {n} дн.",1671
"game.shrinkInDays.one": "Арена сожмётся через {n} день",1672
"game.shrinkInDays.other": "Арена сожмётся через {n} дней",1673
"game.shrinkInDays.few": "Арена сожмётся через {n} дня",1674
"game.shrinkInDays.many": "Арена сожмётся через {n} дней",1675
"game.shrinkTomorrow": "Арена сожмётся завтра",1676
"game.shrinkToday": "Арена сожмётся при следующем начислении",1677
"game.upgrade": "Увеличить дальность",1678
"game.settings": "Настройки",1679
"game.surrender": "Сдаться",1680
"game.surrenderConfirm": "Сдаться? Вы выбудете из этой игры. Это нельзя отменить.",1681
"game.surrenderConfirmBtn": "Да, сдаться",1682
"game.surrenderCancel": "Отмена",1683
"game.back": "Вернуться в меню",1684
"game.spectating": "Вы выбыли. Можно смотреть, писать сообщения и, если жюри включено, голосовать.",1685
"game.ceasefireLeft": "До конца перемирия",1686
"game.ceasefireUntil": "До начала перемирия",1687
"game.ceasefireActive": "Перемирие",1688
"game.attackDisabled": "Атака",1689
"game.attackDisabledReason": "Во время перемирия атаковать нельзя.",1690
"game.selectSelf": "Ваш танк выбран. Нажмите подсвеченную клетку, чтобы пойти, или увеличьте дальность.",1691
"game.impassable": "Непроходимо",1692
"game.willShrink": "Это кольцо сожмётся следующим",1693
"opt.info": "Сведения",1694
"opt.attack": "Атаковать",1695
"opt.give": "Отдать очки действия",1696
"opt.message": "Отправить сообщение",1697
"opt.close": "Закрыть",1698
"info.title": "Сведения",1699
"info.lives": "Жизни",1700
"info.ap": "Очки действия",1701
"info.range": "Дальность",1702
"info.notes": "Ваши личные заметки",1703
"info.notesHint": "Эти заметки видите только вы. Они хранятся в вашем аккаунте.",1704
"info.saveNotes": "Сохранить заметки",1705
"info.saved": "Сохранено",1706
"give.title": "Отдать очки действия",1707
"give.howMany": "Сколько?",1708
"give.send": "Отдать",1709
"give.youHave": "У вас {n}.",1710
"chat.title": "Сообщение для {name}",1711
"chat.placeholder": "Напишите личное сообщение…",1712
"chat.send": "Отправить",1713
"chat.empty": "Сообщений пока нет.",1714
"jury.title": "Жюри",1715
"jury.hint": "Голосуйте за одного живого игрока. Набравший больше всех голосов получит дополнительное очко действия при следующем начислении. Голос можно менять до этого момента. Другие игроки его не видят.",1716
"jury.vote": "Голосовать",1717
"jury.votedFor": "Вы проголосовали за {name}",1718
"jury.change": "Изменить голос",1719
"timeline.play": "Воспроизвести",1720
"timeline.pause": "Пауза",1721
"timeline.live": "Сейчас",1722
"timeline.stepBack": "На шаг назад",1723
"timeline.stepForward": "На шаг вперёд",1724
"timeline.event.start": "Игра начинается",1725
"timeline.event.move": "{name} перемещается",1726
"timeline.event.shoot": "{name} стреляет в {target}",1727
"timeline.event.give": "{name} отдаёт {n} очк. действия игроку {target}",1728
"timeline.event.upgrade": "{name} увеличивает дальность до {n}",1729
"timeline.event.surrender": "{name} сдаётся",1730
"timeline.event.daily": "День {n}: начисление очков действия",1731
"timeline.event.jury": "Жюри присуждает бонус игроку {name}",1732
"timeline.event.juryTie": "Жюри присуждает бонус игрокам {names}",1733
"timeline.event.shrink": "Арена сжимается",1734
"timeline.event.win": "{name} побеждает",1735
"timeline.event.death": "{name} выбывает",1736
"timeline.event.deathShot": "{name} подбит игроком {by}",1737
"timeline.event.deathShrink": "{name} задевает сжимающаяся арена",1738
"timeline.event.deathCrushed": "{name} раздавлен: свободных клеток не осталось",1739
"timeline.event.draw": "Игра заканчивается вничью",1740
"auth.unavailable": "Вход временно недоступен.",1741
"auth.backToGame": "Назад в Allianties",1742
"auth.failed": "Не удалось войти.",1743
"auth.retry": "Попробовать снова",1744
"auth.back": "Назад",1745
"lang.choose": "Выберите язык",1746
"lang.current": "Язык: {name}",1747
"error.login": "Войдите, чтобы продолжить.",1748
"error.csrf": "Сессия истекла. Обновите страницу и попробуйте снова.",1749
"error.not_host": "Это может сделать только хозяин.",1750
"error.min_players": "Для начала нужно как минимум два игрока.",1751
"error.not_in_game": "Вас нет в этой игре.",1752
"error.dead": "Вы выбыли из этой игры.",1753
"error.no_ap": "У вас не осталось очков действия.",1754
"error.occupied": "Эта клетка занята.",1755
"error.impassable": "Эта клетка непроходима.",1756
"error.out_of_range": "Этот игрок вне досягаемости.",1757
"error.invalid_move": "Этот ход недопустим.",1758
"error.game_started": "Эта игра уже началась.",1759
"error.game_finished": "Эта игра уже закончена.",1760
"error.lobby_full": "Это лобби заполнено.",1761
"error.unknown_code": "Лобби с таким кодом не найдено.",1762
"error.cannot_vote": "Сейчас вы не можете голосовать.",1763
"error.bad_vote": "Голосовать можно только за живого игрока.",1764
"error.bad_give": "Столько очков действия отдать нельзя.",1765
"error.unknown_action": "Неизвестное действие.",1766
"error.ceasefire": "Во время перемирия атаковать нельзя.",1767
"error.generic": "Что-то пошло не так. Попробуйте ещё раз.",1768
"error.serverStatus": "Сервер вернул {status}."1769
},1770
"es": {1771
"app.name": "Allianties",1772
"menu.tagline": "Un juego de paciencia, alianzas y disparos bien calculados.",1773
"menu.login": "Iniciar sesión",1774
"menu.logout": "Cerrar sesión",1775
"menu.loggedInAs": "Sesión iniciada como",1776
"menu.localTest": "prueba local:",1777
"menu.create": "Nueva sala",1778
"menu.join": "Unirse",1779
"menu.codePlaceholder": "Código",1780
"menu.myGames": "Tus partidas",1781
"menu.noGames": "Aún no tienes partidas. Crea una sala e invita a otros.",1782
"menu.authUnconfiguredHtml": "El inicio de sesión aún no está configurado en este servidor. Hay que registrar la callback <code>/allianties/callback.php</code> en auth.timfalken.com y configurar el secreto del cliente.",1783
"menu.guestHint": "Inicia sesión para crear una sala, invitar jugadores y empezar una partida duradera.",1784
"menu.open": "Abrir",1785
"menu.continue": "Continuar",1786
"menu.statusLobby": "Sala",1787
"menu.statusRunning": "En juego",1788
"menu.statusFinished": "Terminada",1789
"menu.youWon": "Has ganado",1790
"menu.draw": "Empate",1791
"menu.winnerIs": "Ganador: {name}",1792
"menu.needLogin": "Inicia sesión primero para jugar.",1793
"menu.players": "Jugadores",1794
"lobby.title": "Sala",1795
"lobby.invite": "Invitar",1796
"lobby.copy": "Copiar enlace",1797
"lobby.copied": "Copiado",1798
"lobby.shareHint": "Comparte este código o enlace. Los jugadores inician sesión y se unen.",1799
"lobby.players": "Jugadores",1800
"lobby.start": "Empezar partida",1801
"lobby.leave": "Salir de la sala",1802
"lobby.host": "Anfitrión",1803
"lobby.you": "tú",1804
"lobby.minPlayers": "Hacen falta al menos dos jugadores para empezar.",1805
"lobby.needTwo": "Esperando al menos a un jugador más…",1806
"lobby.rules": "Reglas",1807
"lobby.jury": "Jurado",1808
"lobby.juryHint": "Los jugadores eliminados votan cada día por un jugador vivo. Quien recibe más votos obtiene un punto de acción extra en el siguiente reparto diario. En caso de empate, cada jugador empatado recibe la bonificación. Los votos son secretos y se pueden cambiar hasta entonces.",1809
"lobby.shrink": "Arena que se encoge",1810
"lobby.shrinkHint": "Tras un número configurable de días, el anillo exterior se vuelve intransitable en el reparto diario. Los jugadores que estén encima pierden una vida y son empujados hacia dentro.",1811
"lobby.shrinkDays": "Días entre encogimientos",1812
"lobby.shrinkDaysHint": "El primer encogimiento tras tantas medianoches, y luego cada vez que pasen otros tantos días, hasta el tamaño mínimo de la arena.",1813
"lobby.ceasefire": "Horas de alto el fuego forzoso",1814
"lobby.ceasefireHint": "Durante estas horas (Europe/Amsterdam) nadie puede disparar. Moverse, dar puntos de acción y mejorar el alcance siguen permitidos. Los periodos pueden cruzar la medianoche.",1815
"lobby.ceasefireAdd": "Añadir periodo",1816
"lobby.ceasefireRemove": "Quitar",1817
"lobby.ceasefireStart": "Desde",1818
"lobby.ceasefireEnd": "Hasta",1819
"lobby.ceasefireEmpty": "Aún no hay periodos. Añade uno o arrastra un sector en el reloj.",1820
"lobby.ceasefireClock": "Reloj de 24 horas. Arrastra los tiradores o pinta un sector; el rojo es alto el fuego, el oro es fuego libre. Horarios en Europe/Amsterdam.",1821
"lobby.apLoot": "Saquear puntos de acción al eliminar",1822
"lobby.apLootHint": "Si eliminas a un jugador de un disparo, recibes sus puntos de acción restantes. Rendirse y la arena que se encoge no transfieren puntos. Desactivado por defecto.",1823
"lobby.apTime": "Puntos de acción diarios a las",1824
"lobby.apTimeHint": "Europe/Amsterdam. Los puntos de acción, los bonus del jurado y la reducción de la arena ocurren cada día a esta hora. Por defecto 00:00.",1825
"lobby.visibility": "Visibilidad",1826
"lobby.visibilityHint": "Quién puede ver qué. Siempre ves tus propias vidas, puntos de acción y alcance. El movimiento es siempre público. El servidor oculta el resto a cada espectador; los sucesos ocultos no aparecen en absoluto en la línea de tiempo.",1827
"lobby.visShots": "Disparos",1828
"lobby.visShotsPublic": "Público",1829
"lobby.visShotsElimPublic": "Solo son públicos los disparos que eliminan",1830
"lobby.visShotsKnownTarget": "Solo lo sabe el objetivo",1831
"lobby.visShotsElimKnownTarget": "El objetivo solo conoce los disparos que lo eliminan",1832
"lobby.visGifts": "Regalos",1833
"lobby.visGiftsPublic": "Público",1834
"lobby.visGiftsKnownRecipient": "Solo lo sabe el destinatario",1835
"lobby.visGiftsAnonymous": "Anónimo: el destinatario recibe los puntos pero debe deducir de quién",1836
"lobby.visAp": "Totales de puntos de acción",1837
"lobby.visApPublic": "Público",1838
"lobby.visApHidden": "Oculto",1839
"lobby.visRange": "Alcance",1840
"lobby.visRangePublic": "Público",1841
"lobby.visRangeInRange": "Lo saben los jugadores que están a alcance",1842
"lobby.visRangeHidden": "Oculto",1843
"lobby.visLives": "Vidas",1844
"lobby.visLivesPublic": "Público",1845
"lobby.visLivesHidden": "Oculto",1846
"info.hidden": "Oculto",1847
"lobby.waiting": "Esperando a que el anfitrión empiece la partida.",1848
"lobby.back": "Volver",1849
"lobby.code": "Código",1850
"lobby.playerCount.one": "{n} jugador",1851
"lobby.playerCount.other": "{n} jugadores",1852
"lobby.playerCount.few": "{n} jugadores",1853
"lobby.playerCount.many": "{n} jugadores",1854
"game.day": "Día {n}",1855
"game.nextAp": "Próximos puntos de acción",1856
"game.lives": "Vidas",1857
"game.ap": "Puntos de acción",1858
"game.range": "Alcance",1859
"game.you": "Tú",1860
"game.dead": "Eliminado",1861
"game.surrendered": "Se rindió",1862
"game.winner": "¡{name} gana!",1863
"game.youWin": "¡Has ganado!",1864
"game.draw": "La partida termina en empate.",1865
"game.shrinkIn": "La arena se encoge en {n} días",1866
"game.shrinkInDays.one": "La arena se encoge en {n} día",1867
"game.shrinkInDays.other": "La arena se encoge en {n} días",1868
"game.shrinkInDays.few": "La arena se encoge en {n} días",1869
"game.shrinkInDays.many": "La arena se encoge en {n} días",1870
"game.shrinkTomorrow": "La arena se encoge mañana",1871
"game.shrinkToday": "La arena se encoge en el siguiente reparto",1872
"game.upgrade": "Aumentar alcance",1873
"game.settings": "Ajustes",1874
"game.surrender": "Rendirse",1875
"game.surrenderConfirm": "¿Rendirse? Quedarás fuera de esta partida. No se puede deshacer.",1876
"game.surrenderConfirmBtn": "Sí, rendirme",1877
"game.surrenderCancel": "Cancelar",1878
"game.back": "Volver al menú",1879
"game.spectating": "Estás eliminado. Aún puedes observar, enviar mensajes y, si el jurado está activo, votar.",1880
"game.ceasefireLeft": "Tiempo restante de alto el fuego",1881
"game.ceasefireUntil": "Tiempo hasta el alto el fuego",1882
"game.ceasefireActive": "Alto el fuego",1883
"game.attackDisabled": "Atacar",1884
"game.attackDisabledReason": "No se puede atacar durante las horas de alto el fuego.",1885
"game.selectSelf": "Tu tanque está seleccionado. Toca una casilla destacada para moverte, o aumenta tu alcance.",1886
"game.impassable": "Intransitable",1887
"game.willShrink": "Este anillo se encogerá a continuación",1888
"opt.info": "Info",1889
"opt.attack": "Atacar",1890
"opt.give": "Dar puntos de acción",1891
"opt.message": "Enviar mensaje",1892
"opt.close": "Cerrar",1893
"info.title": "Info",1894
"info.lives": "Vidas",1895
"info.ap": "Puntos de acción",1896
"info.range": "Alcance",1897
"info.notes": "Tus notas privadas",1898
"info.notesHint": "Solo tú puedes ver estas notas. Se guardan con tu cuenta.",1899
"info.saveNotes": "Guardar notas",1900
"info.saved": "Guardado",1901
"give.title": "Dar puntos de acción",1902
"give.howMany": "¿Cuántos?",1903
"give.send": "Dar",1904
"give.youHave": "Tienes {n}.",1905
"chat.title": "Mensaje a {name}",1906
"chat.placeholder": "Escribe un mensaje privado…",1907
"chat.send": "Enviar",1908
"chat.empty": "Aún no hay mensajes.",1909
"jury.title": "Jurado",1910
"jury.hint": "Vota por un jugador vivo. Quien reciba más votos obtiene un punto de acción extra en el siguiente reparto. Puedes cambiar tu voto hasta entonces. Los demás no ven tu voto.",1911
"jury.vote": "Votar",1912
"jury.votedFor": "Has votado por {name}",1913
"jury.change": "Cambiar voto",1914
"timeline.play": "Reproducir",1915
"timeline.pause": "Pausa",1916
"timeline.live": "En directo",1917
"timeline.stepBack": "Un paso atrás",1918
"timeline.stepForward": "Un paso adelante",1919
"timeline.event.start": "Empieza la partida",1920
"timeline.event.move": "{name} se mueve",1921
"timeline.event.shoot": "{name} dispara a {target}",1922
"timeline.event.give": "{name} da {n} punto(s) de acción a {target}",1923
"timeline.event.upgrade": "{name} aumenta el alcance a {n}",1924
"timeline.event.surrender": "{name} se rinde",1925
"timeline.event.daily": "Día {n}: se reparten los puntos de acción",1926
"timeline.event.jury": "El jurado otorga una bonificación a {name}",1927
"timeline.event.juryTie": "El jurado otorga una bonificación a {names}",1928
"timeline.event.shrink": "La arena se encoge",1929
"timeline.event.win": "{name} gana",1930
"timeline.event.death": "{name} queda eliminado",1931
"timeline.event.deathShot": "{by} dispara a {name} y lo elimina",1932
"timeline.event.deathShrink": "{name} es alcanzado por la arena que se encoge",1933
"timeline.event.deathCrushed": "{name} queda aplastado: no queda ninguna casilla libre",1934
"timeline.event.draw": "La partida termina en empate",1935
"auth.unavailable": "El inicio de sesión no está disponible temporalmente.",1936
"auth.backToGame": "Volver a Allianties",1937
"auth.failed": "Error al iniciar sesión.",1938
"auth.retry": "Reintentar",1939
"auth.back": "Volver",1940
"lang.choose": "Elegir idioma",1941
"lang.current": "Idioma: {name}",1942
"error.login": "Inicia sesión para continuar.",1943
"error.csrf": "Tu sesión ha caducado. Actualiza la página e inténtalo de nuevo.",1944
"error.not_host": "Solo el anfitrión puede hacer eso.",1945
"error.min_players": "Hacen falta al menos dos jugadores para empezar.",1946
"error.not_in_game": "No estás en esta partida.",1947
"error.dead": "Has quedado eliminado de esta partida.",1948
"error.no_ap": "No te quedan puntos de acción.",1949
"error.occupied": "Esa casilla está ocupada.",1950
"error.impassable": "Esa casilla es intransitable.",1951
"error.out_of_range": "Ese jugador está fuera de alcance.",1952
"error.invalid_move": "Ese movimiento no está permitido.",1953
"error.game_started": "Esta partida ya ha empezado.",1954
"error.game_finished": "Esta partida ha terminado.",1955
"error.lobby_full": "Esta sala está llena.",1956
"error.unknown_code": "No se encontró ninguna sala con ese código.",1957
"error.cannot_vote": "Ahora no puedes votar.",1958
"error.bad_vote": "Solo puedes votar por un jugador vivo.",1959
"error.bad_give": "No puedes dar tantos puntos de acción.",1960
"error.unknown_action": "Acción desconocida.",1961
"error.ceasefire": "No puedes atacar durante el alto el fuego.",1962
"error.generic": "Algo salió mal. Inténtalo de nuevo.",1963
"error.serverStatus": "El servidor devolvió {status}."1964
}1965
},1966
"errors": {1967
"login": "error.login",1968
"csrf": "error.csrf",1969
"not_host": "error.not_host",1970
"min_players": "error.min_players",1971
"not_in_game": "error.not_in_game",1972
"dead": "error.dead",1973
"no_ap": "error.no_ap",1974
"occupied": "error.occupied",1975
"impassable": "error.impassable",1976
"out_of_range": "error.out_of_range",1977
"invalid_move": "error.invalid_move",1978
"game_started": "error.game_started",1979
"game_finished": "error.game_finished",1980
"lobby_full": "error.lobby_full",1981
"unknown_code": "error.unknown_code",1982
"cannot_vote": "error.cannot_vote",1983
"bad_vote": "error.bad_vote",1984
"bad_give": "error.bad_give",1985
"unknown_action": "error.unknown_action",1986
"ceasefire": "error.ceasefire",1987
"generic": "error.generic"1988
}1989
}@@ -0,0 +1,10 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
logoutUser();
5
if (isset($_GET['json'])) {
6
header('Content-Type: application/json; charset=utf-8');
7
echo json_encode(['ok' => true]);
8
exit;
9
}
10
header('Location: index.html');
@@ -0,0 +1,10 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
logoutUser();5
if (isset($_GET['json'])) {6
header('Content-Type: application/json; charset=utf-8');7
echo json_encode(['ok' => true]);8
exit;9
}10
header('Location: index.html');@@ -0,0 +1,18 @@
1
<?php
2
declare(strict_types=1);
3
// php -S 127.0.0.1:8080 -t build build/router.php
4
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/');
5
$file = __DIR__ . $uri;
6
if ($uri !== '/' && is_file($file)) {
7
return false;
8
}
9
if (str_ends_with($uri, '.php') && is_file($file)) {
10
require $file;
11
return true;
12
}
13
if (is_file(__DIR__ . '/index.html')) {
14
header('Content-Type: text/html; charset=utf-8');
15
readfile(__DIR__ . '/index.html');
16
return true;
17
}
18
return false;
@@ -0,0 +1,18 @@1
<?php2
declare(strict_types=1);3
// php -S 127.0.0.1:8080 -t build build/router.php4
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/');5
$file = __DIR__ . $uri;6
if ($uri !== '/' && is_file($file)) {7
return false;8
}9
if (str_ends_with($uri, '.php') && is_file($file)) {10
require $file;11
return true;12
}13
if (is_file(__DIR__ . '/index.html')) {14
header('Content-Type: text/html; charset=utf-8');15
readfile(__DIR__ . '/index.html');16
return true;17
}18
return false;@@ -0,0 +1,939 @@
1
<?php
2
declare(strict_types=1);
3
require_once dirname(__DIR__) . '/lib/Engine.php';
4
5
$failed = 0;
6
$passed = 0;
7
8
function expect(bool $cond, string $msg): void
9
{
10
global $failed, $passed;
11
if ($cond) {
12
$passed++;
13
echo " ok $msg\n";
14
} else {
15
$failed++;
16
echo " FAIL $msg\n";
17
}
18
}
19
20
function game(array $ids, array $rules = [], ?int $now = null): array
21
{
22
$now = $now ?? 1_700_000_000; // 2023-11-14 22:13:20 UTC — a mid-evening
23
$g = Engine::newLobby('g1', 'ABC234', $ids[0], $ids[0], null, $rules, $now);
24
for ($i = 1; $i < count($ids); $i++) {
25
$g = Engine::join($g, $ids[$i], $ids[$i], null, $now);
26
}
27
$g = Engine::start($g, $ids[0], $now);
28
return $g;
29
}
30
31
echo "Engine: grid and placement\n";
32
expect(Engine::gridSize(2) === 6, '2 players → 6×6');
33
expect(Engine::gridSize(4) === 6, '4 players → 6×6');
34
expect(Engine::gridSize(8) === 7, '8 players → 7×7 (ceil sqrt(48)=7)');
35
expect(Engine::gridSize(12) === 9, '12 players → 9×9 (ceil sqrt(72)=9)');
36
expect(Engine::maxInset(6) === 1, '6×6 max inset 1 (leaves 4×4, min arena 3)');
37
expect(Engine::maxInset(7) === 2, '7×7 max inset 2 (leaves 3×3)');
38
$pos = Engine::startingPositions(4, 6);
39
expect(count($pos) === 4, '4 starting positions');
40
$keys = array_map(fn ($p) => $p['x'] . ',' . $p['y'], $pos);
41
expect(count(array_unique($keys)) === 4, 'starting positions are unique');
42
foreach ($pos as $p) {
43
expect(Engine::inBounds(6, $p['x'], $p['y']), "start in bounds {$p['x']},{$p['y']}");
44
}
45
46
echo "Engine: Chebyshev range\n";
47
expect(Engine::chebyshev(0, 0, 2, 2) === 2, 'diagonal 2 is range 2');
48
expect(Engine::chebyshev(0, 0, 2, 0) === 2, 'orthogonal 2 is range 2');
49
expect(Engine::chebyshev(5, 5, 5, 5) === 0, 'same tile is 0');
50
51
echo "Engine: midnight Amsterdam\n";
52
// 2026-11-13 23:00 CET = 2026-11-13 22:00 UTC = 1763071200? Let's compute.
53
$tz = new DateTimeZone('Europe/Amsterdam');
54
$dt = new DateTime('2026-11-13 23:30:00', $tz);
55
$from = $dt->getTimestamp();
56
$next = Engine::nextMidnight($from);
57
$nx = (new DateTime('@' . $next))->setTimezone($tz);
58
expect($nx->format('Y-m-d H:i:s') === '2026-11-14 00:00:00', 'next midnight after 23:30 is 00:00 next day: ' . $nx->format('Y-m-d H:i:s'));
59
$dt2 = new DateTime('2026-11-14 00:00:00', $tz);
60
$next2 = Engine::nextMidnight($dt2->getTimestamp());
61
$nx2 = (new DateTime('@' . $next2))->setTimezone($tz);
62
expect($nx2->format('Y-m-d H:i:s') === '2026-11-15 00:00:00', 'at exactly 00:00, next is tomorrow');
63
// DST spring-forward 2026-03-29 in NL
64
$dt3 = new DateTime('2026-03-28 23:00:00', $tz);
65
$next3 = Engine::nextMidnight($dt3->getTimestamp());
66
$nx3 = (new DateTime('@' . $next3))->setTimezone($tz);
67
expect($nx3->format('Y-m-d H:i:s') === '2026-03-29 00:00:00', 'DST: next midnight still 00:00: ' . $nx3->format('Y-m-d H:i:s'));
68
69
echo "Engine: lobby and start\n";
70
$now = (new DateTime('2026-11-13 15:00:00', $tz))->getTimestamp();
71
$g = Engine::newLobby('g', 'CODE12', 'a', 'Alice', null, [], $now);
72
expect($g['status'] === 'lobby', 'new lobby');
73
expect($g['rules']['jury'] === true, 'jury default ON');
74
expect($g['rules']['shrinking_arena'] === false, 'shrink default OFF');
75
expect($g['rules']['shrink_interval_days'] === 7, 'shrink interval default 7');
76
expect($g['rules']['ceasefire'] === false, 'ceasefire default OFF');
77
expect($g['rules']['ceasefire_ranges'] === [], 'ceasefire ranges empty by default');
78
expect($g['rules']['vis_shots'] === 'public', 'vis_shots default public');
79
expect($g['rules']['vis_gifts'] === 'public', 'vis_gifts default public');
80
expect($g['rules']['vis_ap'] === 'public', 'vis_ap default public');
81
expect($g['rules']['vis_range'] === 'public', 'vis_range default public');
82
expect($g['rules']['vis_lives'] === 'public', 'vis_lives default public');
83
expect($g['rules']['ap_loot'] === false, 'ap_loot default OFF');
84
expect($g['rules']['ap_time'] === '00:00', 'ap_time default 00:00');
85
expect($g['host_id'] === 'a', 'host is creator');
86
try {
87
Engine::start($g, 'a', $now);
88
expect(false, 'start alone should throw');
89
} catch (RuntimeException $e) {
90
expect($e->getMessage() === 'min_players', 'start alone: min_players');
91
}
92
$g = Engine::join($g, 'b', 'Bob', null, $now);
93
expect(count($g['players']) === 2, '2 players');
94
try {
95
Engine::start($g, 'b', $now);
96
expect(false, 'non-host start');
97
} catch (RuntimeException $e) {
98
expect($e->getMessage() === 'not_host', 'non-host cannot start');
99
}
100
$g = Engine::start($g, 'a', $now);
101
expect($g['status'] === 'running', 'started');
102
expect($g['grid'] === 6, 'grid 6');
103
expect($g['players'][0]['ap'] === 1, 'start with 1 AP');
104
expect($g['players'][0]['lives'] === 3, 'start with 3 lives');
105
expect($g['players'][0]['range'] === 2, 'start with range 2');
106
expect($g['players'][0]['x'] !== $g['players'][1]['x'] || $g['players'][0]['y'] !== $g['players'][1]['y'], 'not overlapping');
107
$nd = (new DateTime('@' . $g['next_distribution_at']))->setTimezone($tz);
108
expect($nd->format('Y-m-d H:i:s') === '2026-11-14 00:00:00', 'next AP at next midnight: ' . $nd->format('Y-m-d H:i:s'));
109
110
echo "Engine: move, blocked, AP\n";
111
$a = $g['players'][0];
112
$legal = Engine::legal($g, 'a');
113
expect(count($legal['move']) >= 1, 'Alice has at least one move');
114
$t = $legal['move'][0];
115
$g2 = Engine::applyAction($g, 'a', ['type' => 'move', 'x' => $t['x'], 'y' => $t['y']], $now);
116
expect($g2['players'][0]['x'] === $t['x'] && $g2['players'][0]['y'] === $t['y'], 'moved');
117
expect($g2['players'][0]['ap'] === 0, 'spent 1 AP');
118
expect(end($g2['events'])['type'] === 'move', 'move event');
119
expect(end($g2['events'])['spend'] === true, 'move is a spend tick');
120
try {
121
Engine::applyAction($g2, 'a', ['type' => 'move', 'x' => $t['x'] + 1, 'y' => $t['y']], $now);
122
expect(false, 'move without AP');
123
} catch (RuntimeException $e) {
124
expect($e->getMessage() === 'no_ap' || $e->getMessage() === 'invalid_move', 'no AP: ' . $e->getMessage());
125
}
126
127
echo "Engine: shoot and death and win\n";
128
// Place two players adjacent, Alice shoots Bob three times (give extra AP).
129
$g = game(['a', 'b'], [], $now);
130
$g['players'][0]['x'] = 2;
131
$g['players'][0]['y'] = 2;
132
$g['players'][0]['ap'] = 5;
133
$g['players'][1]['x'] = 3;
134
$g['players'][1]['y'] = 3;
135
$g['players'][1]['ap'] = 0;
136
$legal = Engine::legal($g, 'a');
137
expect(in_array('b', $legal['shoot'], true), 'Bob is in range 2 (actually dist 1)');
138
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);
139
expect($g['players'][1]['lives'] === 2, 'Bob has 2 lives');
140
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);
141
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);
142
expect($g['players'][1]['alive'] === false, 'Bob is dead');
143
expect($g['status'] === 'finished', 'game finished');
144
expect($g['winner_id'] === 'a', 'Alice wins');
145
$types = array_column($g['events'], 'type');
146
expect(in_array('death', $types, true), 'death event');
147
expect(in_array('win', $types, true), 'win event');
148
149
echo "Engine: give AP and upgrade\n";
150
$g = game(['a', 'b'], [], $now);
151
$g['players'][0]['x'] = 2;
152
$g['players'][0]['y'] = 2;
153
$g['players'][0]['ap'] = 4;
154
$g['players'][1]['x'] = 3;
155
$g['players'][1]['y'] = 2;
156
$g['players'][1]['ap'] = 0;
157
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $now);
158
expect($g['players'][0]['ap'] === 2, 'Alice spent 2');
159
expect($g['players'][1]['ap'] === 2, 'Bob received 2');
160
try {
161
Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 5], $now);
162
expect(false, 'give more than you have');
163
} catch (RuntimeException $e) {
164
expect($e->getMessage() === 'bad_give', 'bad_give');
165
}
166
$g = Engine::applyAction($g, 'a', ['type' => 'upgrade'], $now);
167
expect($g['players'][0]['range'] === 3, 'range is now 3');
168
expect($g['players'][0]['ap'] === 1, 'upgrade costs 1');
169
170
echo "Engine: out of range and occupied\n";
171
$g = game(['a', 'b'], [], $now);
172
$g['players'][0]['x'] = 0;
173
$g['players'][0]['y'] = 0;
174
$g['players'][0]['ap'] = 2;
175
$g['players'][1]['x'] = 5;
176
$g['players'][1]['y'] = 5;
177
$legal = Engine::legal($g, 'a');
178
expect(!in_array('b', $legal['shoot'], true), 'Bob at (5,5) is out of range 2 from (0,0)');
179
try {
180
Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);
181
expect(false, 'shoot out of range');
182
} catch (RuntimeException $e) {
183
expect($e->getMessage() === 'out_of_range', 'out_of_range');
184
}
185
// Occupied neighbour is not a legal move.
186
$g['players'][1]['x'] = 1;
187
$g['players'][1]['y'] = 0;
188
$legal = Engine::legal($g, 'a');
189
$occ = false;
190
foreach ($legal['move'] as $m) {
191
if ($m['x'] === 1 && $m['y'] === 0) {
192
$occ = true;
193
}
194
}
195
expect($occ === false, 'cannot move onto Bob');
196
197
echo "Engine: surrender\n";
198
$g = game(['a', 'b'], [], $now);
199
$g = Engine::applyAction($g, 'b', ['type' => 'surrender'], $now);
200
expect($g['players'][1]['alive'] === false, 'Bob surrendered');
201
expect($g['players'][1]['surrendered'] === true, 'flagged surrendered');
202
expect($g['winner_id'] === 'a', 'Alice wins after surrender');
203
204
echo "Engine: daily AP grant\n";
205
$g = game(['a', 'b'], ['jury' => false], $now);
206
$g['players'][0]['ap'] = 0;
207
$g['players'][1]['ap'] = 0;
208
$at = $g['next_distribution_at'];
209
$g = Engine::applyDue($g, $at);
210
expect($g['day'] === 1, 'day is 1');
211
expect($g['players'][0]['ap'] === 1, 'Alice got 1 AP');
212
expect($g['players'][1]['ap'] === 1, 'Bob got 1 AP');
213
// Catch-up two more midnights
214
$at2 = Engine::nextMidnight($at);
215
$at3 = Engine::nextMidnight($at2);
216
$g = Engine::applyDue($g, $at3);
217
expect($g['day'] === 3, 'caught up to day 3, day=' . $g['day']);
218
expect($g['players'][0]['ap'] === 3, '3 AP after 3 days (started 0): ' . $g['players'][0]['ap']);
219
220
echo "Engine: jury\n";
221
$g = game(['a', 'b', 'c', 'd'], ['jury' => true, 'shrinking_arena' => false], $now);
222
// Kill c and d without ending? Need 4 players, kill only c (one dead voter).
223
// Place and shoot c twice then once more... easier: set lives.
224
$g['players'][2]['lives'] = 0;
225
$g['players'][2]['alive'] = false;
226
$g['players'][2]['ap'] = 0;
227
$g['players'][3]['lives'] = 0;
228
$g['players'][3]['alive'] = false;
229
$g['players'][3]['ap'] = 0;
230
expect($g['status'] === 'running', 'still running with 2 alive');
231
// c votes for a, d votes for a
232
$g = Engine::applyAction($g, 'c', ['type' => 'vote', 'target' => 'a'], $now);
233
$g = Engine::applyAction($g, 'd', ['type' => 'vote', 'target' => 'a'], $now);
234
expect($g['votes']['c'] === 'a', 'c voted a');
235
// Vote is changeable
236
$g = Engine::applyAction($g, 'd', ['type' => 'vote', 'target' => 'b'], $now);
237
expect($g['votes']['d'] === 'b', 'd changed vote to b');
238
// Living player cannot vote
239
try {
240
Engine::applyAction($g, 'a', ['type' => 'vote', 'target' => 'b'], $now);
241
expect(false, 'living vote');
242
} catch (RuntimeException $e) {
243
expect($e->getMessage() === 'cannot_vote', 'living cannot vote');
244
}
245
// Present hides votes from others
246
$viewA = Engine::present($g, 'a');
247
expect($viewA['legal']['my_vote'] === null, 'Alice (living) has no vote');
248
$viewC = Engine::present($g, 'c');
249
expect($viewC['legal']['my_vote'] === 'a', 'Charlie sees own vote');
250
expect(!isset($viewA['votes']), 'votes not in present payload');
251
// Distribution: 1 vote a, 1 vote b → tie, both get +1 bonus (+1 regular) = +2
252
$g['players'][0]['ap'] = 0;
253
$g['players'][1]['ap'] = 0;
254
$g = Engine::applyDue($g, $g['next_distribution_at']);
255
expect($g['players'][0]['ap'] === 2, 'Alice got 1+1 (tie): ' . $g['players'][0]['ap']);
256
expect($g['players'][1]['ap'] === 2, 'Bob got 1+1 (tie): ' . $g['players'][1]['ap']);
257
expect($g['votes'] === [], 'votes reset after distribution');
258
// Unique winner
259
$g['players'][2]['alive'] = false;
260
$g = Engine::applyAction($g, 'c', ['type' => 'vote', 'target' => 'a'], $now + 1);
261
$g = Engine::applyAction($g, 'd', ['type' => 'vote', 'target' => 'a'], $now + 1);
262
$g['players'][0]['ap'] = 0;
263
$g['players'][1]['ap'] = 0;
264
$g = Engine::applyDue($g, $g['next_distribution_at']);
265
expect($g['players'][0]['ap'] === 2, 'Alice unique jury winner: 2');
266
expect($g['players'][1]['ap'] === 1, 'Bob only regular 1: ' . $g['players'][1]['ap']);
267
// Jury off: no vote
268
$gOff = game(['a', 'b', 'c'], ['jury' => false], $now);
269
$gOff['players'][2]['alive'] = false;
270
$gOff['players'][2]['lives'] = 0;
271
try {
272
Engine::applyAction($gOff, 'c', ['type' => 'vote', 'target' => 'a'], $now);
273
expect(false, 'vote with jury off');
274
} catch (RuntimeException $e) {
275
expect($e->getMessage() === 'cannot_vote', 'jury off: cannot_vote');
276
}
277
278
echo "Engine: shrinking arena\n";
279
$g = game(['a', 'b'], ['shrinking_arena' => true, 'shrink_interval_days' => 2, 'jury' => false], $now);
280
expect($g['grid'] === 6, '6×6');
281
expect(Engine::daysUntilShrink($g) === 2, 'shrink in 2 days (interval 2, day 0): ' . (Engine::daysUntilShrink($g) ?? 'null'));
282
// Put Alice on the outer ring (0,0), Bob in the centre (2,2)
283
$g['players'][0]['x'] = 0;
284
$g['players'][0]['y'] = 0;
285
$g['players'][0]['lives'] = 3;
286
$g['players'][0]['ap'] = 0;
287
$g['players'][1]['x'] = 2;
288
$g['players'][1]['y'] = 2;
289
$g['players'][1]['ap'] = 0;
290
// Day 1: no shrink
291
$g = Engine::applyDue($g, $g['next_distribution_at']);
292
expect($g['day'] === 1, 'day 1');
293
expect($g['arena_inset'] === 0, 'no shrink on day 1');
294
expect($g['players'][0]['x'] === 0 && $g['players'][0]['y'] === 0, 'Alice still on (0,0)');
295
expect($g['players'][0]['lives'] === 3, 'Alice still 3 lives');
296
expect(Engine::daysUntilShrink($g) === 1, 'shrink in 1 day');
297
// Day 2: shrink
298
$g = Engine::applyDue($g, $g['next_distribution_at']);
299
expect($g['day'] === 2, 'day 2');
300
expect($g['arena_inset'] === 1, 'inset is 1');
301
expect($g['players'][0]['lives'] === 2, 'Alice lost 1 life: ' . $g['players'][0]['lives']);
302
expect(Engine::isPassable(6, 1, $g['players'][0]['x'], $g['players'][0]['y']), 'Alice pushed inward to passable ' . $g['players'][0]['x'] . ',' . $g['players'][0]['y']);
303
expect(!($g['players'][0]['x'] === 2 && $g['players'][0]['y'] === 2), 'not onto Bob');
304
expect($g['players'][1]['lives'] === 3, 'Bob unhurt in centre');
305
expect($g['players'][0]['ap'] === 2, 'Alice got day-1 and day-2 AP after surviving shrink: ' . $g['players'][0]['ap']);
306
// Outer ring is impassable
307
$legal = Engine::legal($g, $g['players'][0]['id'] === 'a' ? 'a' : 'a');
308
foreach ($legal['move'] as $m) {
309
expect(Engine::isPassable(6, 1, $m['x'], $m['y']), "legal move {$m['x']},{$m['y']} is passable");
310
}
311
// Max one shrink on 6×6 (maxInset=1); day 4 would try again but stop
312
$g = Engine::applyDue($g, $g['next_distribution_at']); // day 3
313
$g = Engine::applyDue($g, $g['next_distribution_at']); // day 4
314
expect($g['arena_inset'] === 1, 'does not shrink past max inset: ' . $g['arena_inset']);
315
expect(Engine::daysUntilShrink($g) === null, 'no upcoming shrink at max');
316
317
echo "Engine: shrink kills and crush and draw\n";
318
$g = game(['a', 'b'], ['shrinking_arena' => true, 'shrink_interval_days' => 1, 'jury' => false], $now);
319
$g['players'][0]['x'] = 0;
320
$g['players'][0]['y'] = 0;
321
$g['players'][0]['lives'] = 1;
322
$g['players'][1]['x'] = 5;
323
$g['players'][1]['y'] = 5;
324
$g['players'][1]['lives'] = 1;
325
$g = Engine::applyDue($g, $g['next_distribution_at']);
326
expect($g['players'][0]['alive'] === false, 'Alice died on shrink (1 life)');
327
expect($g['players'][1]['alive'] === false, 'Bob died on shrink (1 life)');
328
expect($g['status'] === 'finished', 'finished');
329
expect($g['draw'] === true, 'draw when both die in the same shrink');
330
331
echo "Engine: notes and chat privacy\n";
332
$g = game(['a', 'b'], [], $now);
333
$g = Engine::setNote($g, 'a', 'b', 'looks dangerous');
334
$viewA = Engine::present($g, 'a');
335
$viewB = Engine::present($g, 'b');
336
$noteAonB = null;
337
$noteBonB = null;
338
foreach ($viewA['players'] as $p) {
339
if ($p['id'] === 'b') {
340
$noteAonB = $p['note'];
341
}
342
}
343
foreach ($viewB['players'] as $p) {
344
if ($p['id'] === 'b') {
345
$noteBonB = $p['note'];
346
}
347
}
348
expect($noteAonB === 'looks dangerous', 'Alice sees her note on Bob');
349
expect($noteBonB === '', 'Bob does not see Alice’s note');
350
$g = Engine::addMessage($g, 'a', 'b', 'hello', $now);
351
$viewA = Engine::present($g, 'a');
352
$viewB = Engine::present($g, 'b');
353
expect(count($viewA['messages']) === 1 && $viewA['messages'][0]['text'] === 'hello', 'Alice sees chat');
354
expect(count($viewB['messages']) === 1, 'Bob sees chat');
355
// A third player would not — add c in lobby... already started. Fine.
356
357
echo "Engine: modular rule flags\n";
358
$r = Engine::normalizeRules(['jury' => '0', 'shrinking_arena' => '1', 'shrink_interval_days' => 99, 'ceasefire' => '1']);
359
expect($r['jury'] === false, 'jury "0" is false');
360
expect($r['shrinking_arena'] === true, 'shrink "1" is true');
361
expect($r['shrink_interval_days'] === 30, 'interval clamped to max 30: ' . $r['shrink_interval_days']);
362
expect($r['ceasefire'] === true, 'ceasefire "1" is true');
363
364
echo "Engine: cease-fire ranges and midnight wrap\n";
365
$ranges = Engine::normalizeRanges([
366
['start' => '22:00', 'end' => '06:00'],
367
['start' => '12:00', 'end' => '13:30'],
368
['start' => '25:00', 'end' => '01:00'], // invalid
369
['start' => '08:00', 'end' => '08:00'], // zero-length dropped
370
]);
371
expect(count($ranges) === 2, '2 valid ranges: ' . count($ranges));
372
expect($ranges[0]['start'] === '12:00', 'sorted, first is 12:00');
373
expect($ranges[1]['start'] === '22:00', 'wrap range kept');
374
375
$g = game(['a', 'b'], [
376
'jury' => false,
377
'ceasefire' => true,
378
'ceasefire_ranges' => [
379
['start' => '22:00', 'end' => '06:00'],
380
['start' => '12:00', 'end' => '13:00'],
381
],
382
], $now);
383
// Place adjacent so shoot would otherwise be legal.
384
$g['players'][0]['x'] = 2;
385
$g['players'][0]['y'] = 2;
386
$g['players'][0]['ap'] = 3;
387
$g['players'][1]['x'] = 3;
388
$g['players'][1]['y'] = 2;
389
390
// 2026-11-13 23:30 Amsterdam — inside 22:00-06:00 wrap
391
$inCf = (new DateTime('2026-11-13 23:30:00', $tz))->getTimestamp();
392
$info = Engine::ceasefireInfo($g, $inCf);
393
expect($info !== null && $info['active'] === true, '23:30 is cease-fire (wrap)');
394
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);
395
expect($end->format('Y-m-d H:i') === '2026-11-14 06:00', 'ends at 06:00 next day: ' . $end->format('Y-m-d H:i'));
396
$legal = Engine::legal($g, 'a', $inCf);
397
expect($legal['shoot'] === [], 'Attack disabled during cease-fire');
398
expect($legal['ceasefire'] === true, 'legal.ceasefire true');
399
expect(count($legal['move']) >= 1 || $legal['upgrade'] || true, 'non-shoot actions still considered');
400
// Move is still allowed
401
$legalMove = $legal['move'];
402
expect(!empty($legalMove), 'can still move during cease-fire');
403
try {
404
Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $inCf);
405
expect(false, 'shoot during cease-fire should throw');
406
} catch (RuntimeException $e) {
407
expect($e->getMessage() === 'ceasefire', 'error code ceasefire: ' . $e->getMessage());
408
}
409
410
// 2026-11-14 06:00 exactly — end is exclusive, so not active
411
$atEnd = (new DateTime('2026-11-14 06:00:00', $tz))->getTimestamp();
412
$info = Engine::ceasefireInfo($g, $atEnd);
413
expect($info['active'] === false, '06:00 exactly is not cease-fire (end exclusive)');
414
$until = (new DateTime('@' . $info['until']))->setTimezone($tz);
415
expect($until->format('H:i') === '12:00', 'next cease-fire at 12:00: ' . $until->format('H:i'));
416
417
// 12:30 — second range
418
$noon = (new DateTime('2026-11-14 12:30:00', $tz))->getTimestamp();
419
$info = Engine::ceasefireInfo($g, $noon);
420
expect($info['active'] === true, '12:30 is cease-fire');
421
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);
422
expect($end->format('H:i') === '13:00', 'ends 13:00: ' . $end->format('H:i'));
423
424
// 15:00 — free, next is 22:00 same day
425
$afternoon = (new DateTime('2026-11-14 15:00:00', $tz))->getTimestamp();
426
$info = Engine::ceasefireInfo($g, $afternoon);
427
expect($info['active'] === false, '15:00 is free');
428
$until = (new DateTime('@' . $info['until']))->setTimezone($tz);
429
expect($until->format('Y-m-d H:i') === '2026-11-14 22:00', 'until 22:00: ' . $until->format('Y-m-d H:i'));
430
$legal = Engine::legal($g, 'a', $afternoon);
431
expect(in_array('b', $legal['shoot'], true), 'can shoot when not in cease-fire');
432
$g2 = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $afternoon);
433
expect($g2['players'][1]['lives'] === 2, 'shot landed outside cease-fire');
434
435
// Just before midnight wrap: 21:59 — until 22:00
436
$before = (new DateTime('2026-11-14 21:59:00', $tz))->getTimestamp();
437
$info = Engine::ceasefireInfo($g, $before);
438
expect($info['active'] === false, '21:59 is free');
439
expect($info['seconds'] === 60, '60 seconds until cease-fire: ' . $info['seconds']);
440
441
// 05:59 next morning: 60 seconds left IN cease-fire
442
$late = (new DateTime('2026-11-15 05:59:00', $tz))->getTimestamp();
443
$info = Engine::ceasefireInfo($g, $late);
444
expect($info['active'] === true, '05:59 still cease-fire');
445
expect($info['seconds'] === 60, '60 seconds left in cease-fire: ' . $info['seconds']);
446
447
echo "Engine: cease-fire DST spring-forward (2026-03-29 02:00→03:00)\n";
448
// Range 01:00-04:00 on spring-forward day: 02:00 does not exist, period is 2 hours of real time.
449
$gD = game(['a', 'b'], [
450
'ceasefire' => true,
451
'ceasefire_ranges' => [['start' => '01:00', 'end' => '04:00']],
452
'jury' => false,
453
], $now);
454
$start = (new DateTime('2026-03-29 01:00:00', $tz))->getTimestamp();
455
$info = Engine::ceasefireInfo($gD, $start);
456
expect($info['active'] === true, '01:00 CEST-transition day is cease-fire');
457
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);
458
expect($end->format('Y-m-d H:i') === '2026-03-29 04:00', 'ends 04:00: ' . $end->format('Y-m-d H:i'));
459
// Real duration should be 2 hours (01:00 CET + skipped 02:00 hour → 04:00 CEST)
460
// 01:00 on that day is still CET (UTC+1), 04:00 is CEST (UTC+2).
461
$dur = $info['until'] - $start;
462
expect($dur === 2 * 3600, 'spring-forward 01:00-04:00 is 2 real hours: ' . $dur);
463
// 02:30 does not exist; 03:00 should still be inside
464
$three = (new DateTime('2026-03-29 03:00:00', $tz))->getTimestamp();
465
$info = Engine::ceasefireInfo($gD, $three);
466
expect($info['active'] === true, '03:00 (after the jump) is still cease-fire');
467
expect($info['seconds'] === 3600, '1 hour left at 03:00: ' . $info['seconds']);
468
// Before: 00:30, until 01:00 = 30 min
469
$half = (new DateTime('2026-03-29 00:30:00', $tz))->getTimestamp();
470
$info = Engine::ceasefireInfo($gD, $half);
471
expect($info['active'] === false, '00:30 is free');
472
expect($info['seconds'] === 1800, '30 min until 01:00: ' . $info['seconds']);
473
474
echo "Engine: cease-fire DST fall-back (2026-10-25 03:00→02:00)\n";
475
// Range 01:00-03:30. The 02:00 hour happens twice. amsterdamWallclock adds minutes
476
// from midnight, so 03:30 is unambiguous (after the fallback). Duration:
477
// midnight CEST 00:00 = UTC 22:00 previous; +3.5h = 03:30 CET? Let's assert via DateTime.
478
$gF = game(['a', 'b'], [
479
'ceasefire' => true,
480
'ceasefire_ranges' => [['start' => '01:00', 'end' => '03:30']],
481
'jury' => false,
482
], $now);
483
$fbStart = (new DateTime('2026-10-25 01:00:00', $tz))->getTimestamp();
484
$info = Engine::ceasefireInfo($gF, $fbStart);
485
expect($info['active'] === true, '01:00 fall-back day is cease-fire');
486
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);
487
expect($end->format('Y-m-d H:i') === '2026-10-25 03:30', 'ends 03:30: ' . $end->format('Y-m-d H:i'));
488
$dur = $info['until'] - $fbStart;
489
// 01:00 CEST (UTC 23:00) to 03:30 CET (UTC 02:30) = 3.5 hours (the 02:00 hour repeats).
490
expect($dur === (int) (3.5 * 3600), 'fall-back 01:00-03:30 is 3.5 real hours: ' . $dur);
491
// A moment during the repeated 02:xx should still be active.
492
// 02:15 CEST (first) = 01:00 CEST + 75 min.
493
$first215 = $fbStart + 75 * 60;
494
$info = Engine::ceasefireInfo($gF, $first215);
495
expect($info['active'] === true, 'first 02:15 (still DST) is cease-fire');
496
// 02:15 CET (second) = 01:00 + 75 min + 60 min (the repeated hour)
497
$second215 = $fbStart + (75 + 60) * 60;
498
$info = Engine::ceasefireInfo($gF, $second215);
499
expect($info['active'] === true, 'second 02:15 (CET) is still cease-fire');
500
// After 03:30 CET: free
501
$after = (new DateTime('2026-10-25 03:30:00', $tz))->getTimestamp();
502
$info = Engine::ceasefireInfo($gF, $after);
503
expect($info['active'] === false, '03:30 exactly is free (end exclusive)');
504
505
echo "Engine: cease-fire off or empty ranges\n";
506
$gN = game(['a', 'b'], ['ceasefire' => false, 'ceasefire_ranges' => [['start' => '00:00', 'end' => '23:59']]], $now);
507
expect(Engine::ceasefireInfo($gN, $now) === null, 'rule off → no info (ranges ignored)');
508
$gE = game(['a', 'b'], ['ceasefire' => true, 'ceasefire_ranges' => []], $now);
509
expect(Engine::ceasefireInfo($gE, $now) === null, 'on but empty ranges → treated as no cease-fire');
510
511
echo "Engine: overlapping ranges merge for countdown\n";
512
$gM = game(['a', 'b'], [
513
'ceasefire' => true,
514
'ceasefire_ranges' => [
515
['start' => '10:00', 'end' => '12:00'],
516
['start' => '11:00', 'end' => '13:00'],
517
],
518
'jury' => false,
519
], $now);
520
$t = (new DateTime('2026-11-14 10:30:00', $tz))->getTimestamp();
521
$info = Engine::ceasefireInfo($gM, $t);
522
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);
523
expect($end->format('H:i') === '13:00', 'merged overlapping ends at 13:00: ' . $end->format('H:i'));
524
525
526
echo "Engine: visibility defaults and invalid values fall back to public\n";
527
$norm = Engine::normalizeRules([
528
'vis_shots' => 'nope',
529
'vis_gifts' => 123,
530
'vis_ap' => 'PUBLIC',
531
'vis_range' => '',
532
'vis_lives' => null,
533
]);
534
expect($norm['vis_shots'] === 'public', 'bad vis_shots → public');
535
expect($norm['vis_gifts'] === 'public', 'bad vis_gifts → public');
536
expect($norm['vis_ap'] === 'public', 'bad vis_ap → public');
537
expect($norm['vis_range'] === 'public', 'bad vis_range → public');
538
expect($norm['vis_lives'] === 'public', 'bad vis_lives → public');
539
$ok = Engine::normalizeRules([
540
'vis_shots' => 'elim_known_target',
541
'vis_gifts' => 'anonymous',
542
'vis_ap' => 'hidden',
543
'vis_range' => 'known_in_range',
544
'vis_lives' => 'hidden',
545
]);
546
expect($ok['vis_shots'] === 'elim_known_target', 'accepts elim_known_target');
547
expect($ok['vis_gifts'] === 'anonymous', 'accepts anonymous');
548
expect($ok['vis_ap'] === 'hidden', 'accepts hidden AP');
549
expect($ok['vis_range'] === 'known_in_range', 'accepts known_in_range');
550
expect($ok['vis_lives'] === 'hidden', 'accepts hidden lives');
551
552
/**
553
* Three-player game with A next to B (in starting range 2) and C far away.
554
* Extra AP so we can shoot/give/upgrade more than once.
555
*
556
* @return array{0:array,1:int}
557
*/
558
function visGame(array $vis, int $now): array
559
{
560
$g = game(['a', 'b', 'c'], array_merge(['jury' => false], $vis), $now);
561
// Place: A at (2,2), B at (3,2) dist 1, C at (5,5) dist 3 from A.
562
foreach ($g['players'] as $i => $p) {
563
if ($p['id'] === 'a') {
564
$g['players'][$i]['x'] = 2;
565
$g['players'][$i]['y'] = 2;
566
$g['players'][$i]['ap'] = 5;
567
$g['players'][$i]['range'] = 2;
568
} elseif ($p['id'] === 'b') {
569
$g['players'][$i]['x'] = 3;
570
$g['players'][$i]['y'] = 2;
571
$g['players'][$i]['ap'] = 5;
572
$g['players'][$i]['range'] = 2;
573
} else {
574
$g['players'][$i]['x'] = 5;
575
$g['players'][$i]['y'] = 5;
576
$g['players'][$i]['ap'] = 5;
577
$g['players'][$i]['range'] = 2;
578
}
579
}
580
return [$g, $now];
581
}
582
583
function visEvents(array $view, string $type): array
584
{
585
return array_values(array_filter($view['events'] ?? [], fn ($e) => ($e['type'] ?? '') === $type));
586
}
587
588
function visPlayer(array $view, string $id): ?array
589
{
590
foreach ($view['players'] as $p) {
591
if ($p['id'] === $id) {
592
return $p;
593
}
594
}
595
return null;
596
}
597
598
echo "Engine: vis shots — public (everyone sees, including lives_left when lives public)\n";
599
[$g, $t] = visGame(['vis_shots' => 'public'], $now);
600
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
601
$va = Engine::present($g, 'a', $t);
602
$vb = Engine::present($g, 'b', $t);
603
$vc = Engine::present($g, 'c', $t);
604
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees public shot');
605
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees public shot');
606
expect(count(visEvents($vc, 'shoot')) === 1, 'third party sees public shot');
607
expect(($vc['events'] === visEvents($vc, 'shoot') ? true : isset(visEvents($vc, 'shoot')[0]['player'])) && visEvents($vc, 'shoot')[0]['player'] === 'a', 'third party sees shooter id');
608
expect(visEvents($vc, 'shoot')[0]['lives_left'] === 2, 'public lives_left on shot');
609
expect(visEvents($vc, 'shoot')[0]['damage'] === 1, 'damage is 1');
610
expect(visPlayer($vc, 'b')['lives'] === 2, 'public lives in state');
611
612
echo "Engine: vis shots — elim_public (non-elim hidden from third party, visible to target)\n";
613
[$g, $t] = visGame(['vis_shots' => 'elim_public'], $now);
614
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
615
$va = Engine::present($g, 'a', $t);
616
$vb = Engine::present($g, 'b', $t);
617
$vc = Engine::present($g, 'c', $t);
618
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees non-elim');
619
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees non-elim under elim_public');
620
expect(count(visEvents($vc, 'shoot')) === 0, 'third party does not see non-elim');
621
expect(count(visEvents($vc, 'death')) === 0, 'no death on non-elim');
622
// Two more shots to eliminate (B started with 3, now 2).
623
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
624
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
625
$vc = Engine::present($g, 'c', $t);
626
$vb = Engine::present($g, 'b', $t);
627
$shotsC = visEvents($vc, 'shoot');
628
expect(count($shotsC) === 1, 'third party sees only the eliminating shot: ' . count($shotsC));
629
expect(!empty($shotsC[0]['killed']), 'the visible shot is the kill');
630
expect(count(visEvents($vc, 'death')) === 1, 'third party sees death');
631
expect((visEvents($vc, 'death')[0]['by'] ?? null) === 'a', 'elim_public death includes killer');
632
expect((visEvents($vb, 'death')[0]['by'] ?? null) === 'a', 'target sees killer');
633
expect(visPlayer($vc, 'b')['alive'] === false, 'death/alive is always public');
634
635
echo "Engine: vis shots — known_target (others never see the shot, death without by)\n";
636
[$g, $t] = visGame(['vis_shots' => 'known_target'], $now);
637
$g['players'][array_key_first(array_filter($g['players'], fn ($p) => $p['id'] === 'b'))]['lives'] = 1;
638
// find b index properly
639
foreach ($g['players'] as $i => $p) {
640
if ($p['id'] === 'b') {
641
$g['players'][$i]['lives'] = 1;
642
}
643
}
644
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
645
$va = Engine::present($g, 'a', $t);
646
$vb = Engine::present($g, 'b', $t);
647
$vc = Engine::present($g, 'c', $t);
648
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees known_target shot');
649
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees known_target shot');
650
expect(count(visEvents($vc, 'shoot')) === 0, 'third party does not see known_target shot');
651
$deaths = visEvents($vc, 'death');
652
expect(count($deaths) === 1, 'third party still sees that B died');
653
expect(!array_key_exists('by', $deaths[0]), 'killer stripped for third party under known_target');
654
expect((visEvents($vb, 'death')[0]['by'] ?? null) === 'a', 'target still sees who shot them');
655
656
echo "Engine: vis shots — elim_known_target (non-elim hidden even from target)\n";
657
[$g, $t] = visGame(['vis_shots' => 'elim_known_target'], $now);
658
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
659
$va = Engine::present($g, 'a', $t);
660
$vb = Engine::present($g, 'b', $t);
661
$vc = Engine::present($g, 'c', $t);
662
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees non-elim under elim_known_target');
663
expect(count(visEvents($vb, 'shoot')) === 0, 'target does NOT see non-elim shot (must deduce)');
664
expect(count(visEvents($vc, 'shoot')) === 0, 'third party does not see non-elim');
665
expect(visPlayer($vb, 'b')['lives'] === 2, 'target still sees own lives drop');
666
expect(visPlayer($vc, 'b')['lives'] === 2, 'lives still public in this game (default)');
667
// Eliminate
668
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
669
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
670
$vb = Engine::present($g, 'b', $t);
671
$vc = Engine::present($g, 'c', $t);
672
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees only the eliminating shot');
673
expect((visEvents($vb, 'shoot')[0]['player'] ?? null) === 'a', 'elim shot names the shooter for the target');
674
expect(count(visEvents($vc, 'shoot')) === 0, 'third party never sees shots under elim_known_target');
675
expect(!array_key_exists('by', visEvents($vc, 'death')[0]), 'third party death has no by');
676
677
echo "Engine: vis shots + hidden lives — lives_left stripped except for the target\n";
678
[$g, $t] = visGame(['vis_shots' => 'public', 'vis_lives' => 'hidden'], $now);
679
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
680
$va = Engine::present($g, 'a', $t);
681
$vb = Engine::present($g, 'b', $t);
682
$vc = Engine::present($g, 'c', $t);
683
expect(!array_key_exists('lives_left', visEvents($va, 'shoot')[0]), 'shooter does not get target lives_left');
684
expect((visEvents($vb, 'shoot')[0]['lives_left'] ?? null) === 2, 'target sees own lives_left');
685
expect(!array_key_exists('lives_left', visEvents($vc, 'shoot')[0]), 'third party does not get lives_left');
686
expect(visEvents($va, 'shoot')[0]['damage'] === 1, 'shooter still sees damage 1');
687
expect(visPlayer($va, 'a')['lives'] === 3, 'own lives always visible');
688
expect(visPlayer($va, 'b')['lives'] === null, 'other lives hidden from shooter');
689
expect(visPlayer($vc, 'b')['lives'] === null, 'other lives hidden from third party');
690
expect(visPlayer($vb, 'b')['lives'] === 2, 'target sees own lives');
691
expect(is_bool(visPlayer($vc, 'b')['alive']), 'alive flag still present when lives hidden');
692
693
echo "Engine: vis gifts — public, known_recipient, anonymous\n";
694
[$g, $t] = visGame(['vis_gifts' => 'public'], $now);
695
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $t);
696
$vc = Engine::present($g, 'c', $t);
697
$gives = visEvents($vc, 'give');
698
expect(count($gives) === 1 && $gives[0]['player'] === 'a' && $gives[0]['amount'] === 2, 'public gift visible to third party with giver and amount');
699
700
[$g, $t] = visGame(['vis_gifts' => 'known_recipient'], $now);
701
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $t);
702
$va = Engine::present($g, 'a', $t);
703
$vb = Engine::present($g, 'b', $t);
704
$vc = Engine::present($g, 'c', $t);
705
expect(count(visEvents($va, 'give')) === 1 && visEvents($va, 'give')[0]['player'] === 'a', 'giver sees own gift');
706
expect(count(visEvents($vb, 'give')) === 1 && visEvents($vb, 'give')[0]['player'] === 'a', 'recipient sees giver');
707
expect(count(visEvents($vc, 'give')) === 0, 'third party does not see known_recipient gift');
708
709
[$g, $t] = visGame(['vis_gifts' => 'anonymous'], $now);
710
$beforeB = Engine::player($g, 'b')['ap'];
711
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $t);
712
$va = Engine::present($g, 'a', $t);
713
$vb = Engine::present($g, 'b', $t);
714
$vc = Engine::present($g, 'c', $t);
715
expect(count(visEvents($va, 'give')) === 1 && visEvents($va, 'give')[0]['player'] === 'a', 'giver sees full anonymous gift in their own log');
716
$rec = visEvents($vb, 'give');
717
expect(count($rec) === 1, 'recipient sees an anonymous gift event');
718
expect(!empty($rec[0]['anonymous']), 'event marked anonymous');
719
expect(!array_key_exists('player', $rec[0]), 'giver id stripped for recipient');
720
expect(($rec[0]['amount'] ?? 0) === 2, 'recipient sees the AP amount');
721
expect(($rec[0]['target'] ?? '') === 'b', 'recipient is named as target');
722
expect(count(visEvents($vc, 'give')) === 0, 'third party does not see anonymous gift');
723
expect(visPlayer($vb, 'b')['ap'] === $beforeB + 2, 'recipient AP actually increased');
724
// Stored (unfiltered) event still has the giver — present() must not mutate.
725
$rawGive = null;
726
foreach ($g['events'] as $e) {
727
if (($e['type'] ?? '') === 'give') {
728
$rawGive = $e;
729
}
730
}
731
expect($rawGive !== null && ($rawGive['player'] ?? null) === 'a', 'stored event still has the giver (present does not mutate)');
732
expect(!array_key_exists('player', $rec[0]) || $rec[0]['player'] !== 'a' || true, 'sanity');
733
expect(($rawGive['player'] ?? null) === 'a' && !array_key_exists('player', $rec[0]), 'clone is independent of stored event');
734
735
echo "Engine: vis AP totals hidden\n";
736
[$g, $t] = visGame(['vis_ap' => 'hidden'], $now);
737
$va = Engine::present($g, 'a', $t);
738
$vc = Engine::present($g, 'c', $t);
739
expect(visPlayer($va, 'a')['ap'] === 5, 'own AP visible when hidden rule is on');
740
expect(visPlayer($va, 'b')['ap'] === null, 'other AP hidden');
741
expect(visPlayer($vc, 'a')['ap'] === null, 'third party does not see A’s AP');
742
// Daily grants: only the viewer’s own grant is included.
743
$midnight = Engine::nextMidnight($t);
744
$g = Engine::applyDue($g, $midnight);
745
$va = Engine::present($g, 'a', $midnight);
746
$dailies = visEvents($va, 'daily');
747
expect(count($dailies) === 1, 'daily event present');
748
expect(array_keys($dailies[0]['grants']) === ['a'], 'hidden AP: only own grant in daily event: ' . json_encode($dailies[0]['grants']));
749
expect(!isset($dailies[0]['jury']['counts']), 'jury vote counts stripped');
750
751
echo "Engine: vis range — hidden and known_in_range\n";
752
[$g, $t] = visGame(['vis_range' => 'hidden'], $now);
753
$g = Engine::applyAction($g, 'a', ['type' => 'upgrade'], $t);
754
$va = Engine::present($g, 'a', $t);
755
$vc = Engine::present($g, 'c', $t);
756
expect(visPlayer($va, 'a')['range'] === 3, 'own range after upgrade');
757
expect(visPlayer($vc, 'a')['range'] === null, 'other range hidden');
758
expect(count(visEvents($va, 'upgrade')) === 1, 'upgrader sees own upgrade');
759
expect(count(visEvents($vc, 'upgrade')) === 0, 'third party does not see hidden upgrade');
760
761
[$g, $t] = visGame(['vis_range' => 'known_in_range'], $now);
762
$va = Engine::present($g, 'a', $t);
763
$vb = Engine::present($g, 'b', $t);
764
$vc = Engine::present($g, 'c', $t);
765
// B is at dist 1 from A (range 2) so A is in B’s range and B is in A’s range.
766
expect(visPlayer($vb, 'a')['range'] === 2, 'B is within A’s range, sees A’s range');
767
expect(visPlayer($va, 'b')['range'] === 2, 'A is within B’s range, sees B’s range');
768
expect(visPlayer($vc, 'a')['range'] === null, 'C is outside A’s range (dist 3 > 2)');
769
expect(visPlayer($va, 'c')['range'] === null, 'A is outside C’s range (dist 3 > 2)');
770
expect(visPlayer($vc, 'c')['range'] === 2, 'C always sees own range');
771
// Upgrade A to range 3: C (dist 3) is now in A’s range.
772
$g = Engine::applyAction($g, 'a', ['type' => 'upgrade'], $t);
773
$vc = Engine::present($g, 'c', $t);
774
$va = Engine::present($g, 'a', $t);
775
expect(visPlayer($vc, 'a')['range'] === 3, 'after upgrade, C is within A’s range and sees it');
776
expect(count(visEvents($vc, 'upgrade')) === 1, 'C now also sees the upgrade event');
777
expect(visPlayer($va, 'c')['range'] === null, 'A is still outside C’s range 2');
778
779
echo "Engine: movement is always public, even with everything hidden\n";
780
[$g, $t] = visGame([
781
'vis_shots' => 'elim_known_target',
782
'vis_gifts' => 'anonymous',
783
'vis_ap' => 'hidden',
784
'vis_range' => 'hidden',
785
'vis_lives' => 'hidden',
786
], $now);
787
// A moves to (2,3) — adjacent empty.
788
$g = Engine::applyAction($g, 'a', ['type' => 'move', 'x' => 2, 'y' => 3], $t);
789
$vc = Engine::present($g, 'c', $t);
790
$moves = visEvents($vc, 'move');
791
expect(count($moves) === 1, 'move is public');
792
expect($moves[0]['player'] === 'a' && $moves[0]['to']['x'] === 2 && $moves[0]['to']['y'] === 3, 'move names the player and destination');
793
expect(visPlayer($vc, 'a')['x'] === 2 && visPlayer($vc, 'a')['y'] === 3, 'new position is in the public state');
794
expect(visPlayer($vc, 'a')['ap'] === null, 'AP still hidden after the move');
795
expect(visPlayer($vc, 'a')['lives'] === null, 'lives still hidden');
796
expect(visPlayer($vc, 'a')['range'] === null, 'range still hidden');
797
798
echo "Engine: present() does not leak hidden keys with real values\n";
799
[$g, $t] = visGame(['vis_ap' => 'hidden', 'vis_lives' => 'hidden', 'vis_range' => 'hidden'], $now);
800
$vc = Engine::present($g, 'c', $t);
801
$encoded = json_encode($vc);
802
expect(visPlayer($vc, 'a')['ap'] === null, 'JSON-facing ap is null');
803
expect(visPlayer($vc, 'a')['lives'] === null, 'JSON-facing lives is null');
804
expect(visPlayer($vc, 'a')['range'] === null, 'JSON-facing range is null');
805
// The raw numbers for A (ap=5, lives=3, range=2) must not appear attached to A in a leaky way
806
// — we only require the structured fields are null, which json_encode will emit as null.
807
$decoded = json_decode($encoded, true);
808
foreach ($decoded['players'] as $p) {
809
if ($p['id'] !== 'c') {
810
expect($p['ap'] === null && $p['lives'] === null && $p['range'] === null, "no numeric secrets for {$p['id']}");
811
}
812
}
813
814
815
816
echo "Engine: nextDistribution (per-lobby AP time) and DST\n";
817
$tz = new DateTimeZone('Europe/Amsterdam');
818
$from = (new DateTime('2026-11-14 14:00:00', $tz))->getTimestamp();
819
$nx = Engine::nextDistribution($from, '15:00');
820
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');
821
expect($got === '2026-11-14 15:00:00', "14:00 → today 15:00: $got");
822
$at = (new DateTime('2026-11-14 15:00:00', $tz))->getTimestamp();
823
$nx = Engine::nextDistribution($at, '15:00');
824
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');
825
expect($got === '2026-11-15 15:00:00', "exactly 15:00 → tomorrow 15:00: $got");
826
$from2 = (new DateTime('2026-11-14 16:00:00', $tz))->getTimestamp();
827
$nx = Engine::nextDistribution($from2, '15:00');
828
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');
829
expect($got === '2026-11-15 15:00:00', "16:00 → tomorrow 15:00: $got");
830
// 00:00 matches nextMidnight
831
$eve = (new DateTime('2026-11-13 23:30:00', $tz))->getTimestamp();
832
expect(Engine::nextDistribution($eve, '00:00') === Engine::nextMidnight($eve), '00:00 path equals nextMidnight');
833
expect(Engine::normalizeRules(['ap_time' => '7:05'])['ap_time'] === '07:05', 'ap_time normalised to HH:MM');
834
expect(Engine::normalizeRules(['ap_time' => 'nope'])['ap_time'] === '00:00', 'bad ap_time → 00:00');
835
expect(Engine::normalizeRules(['ap_time' => '24:00'])['ap_time'] === '00:00', '24:00 invalid → 00:00');
836
837
// DST spring-forward 2026-03-29 02:00–03:00 skipped.
838
$before = (new DateTime('2026-03-29 01:30:00', $tz))->getTimestamp();
839
$nx = Engine::nextDistribution($before, '02:30');
840
$gotDt = (new DateTime('@' . $nx))->setTimezone($tz);
841
// 02:30 does not exist; PHP setTime lands on or after the gap (03:30 CEST typically).
842
expect($gotDt->getTimestamp() > $before, 'DST spring: 02:30 candidate is strictly after 01:30');
843
expect($gotDt->format('Y-m-d') === '2026-03-29', 'DST spring: still that calendar day: ' . $gotDt->format('Y-m-d H:i:s T'));
844
// A legal time after the gap is exact.
845
$nx = Engine::nextDistribution($before, '04:00');
846
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');
847
expect($got === '2026-03-29 04:00:00', "DST spring: 04:00 exact: $got");
848
// Fall-back 2026-10-25: 02:30 exists twice; we just need a valid instant that day after 01:30.
849
$fb = (new DateTime('2026-10-25 01:30:00', $tz))->getTimestamp();
850
$nx = Engine::nextDistribution($fb, '02:30');
851
$gotDt = (new DateTime('@' . $nx))->setTimezone($tz);
852
expect($gotDt->format('Y-m-d') === '2026-10-25' && (int) $gotDt->format('H') === 2 && (int) $gotDt->format('i') === 30,
853
'DST fall-back: 02:30 that day: ' . $gotDt->format('Y-m-d H:i:s T'));
854
855
echo "Engine: AP at a non-midnight lobby time\n";
856
$t15 = (new DateTime('2026-11-14 14:00:00', $tz))->getTimestamp();
857
$g = game(['a', 'b'], ['ap_time' => '15:00', 'jury' => false], $t15);
858
expect((int) $g['next_distribution_at'] === Engine::nextDistribution($t15, '15:00'), 'start schedules 15:00');
859
$apA = Engine::player($g, 'a')['ap'];
860
$g2 = Engine::applyDue($g, Engine::nextDistribution($t15, '15:00'));
861
expect((int) $g2['day'] === 1, 'day increments at 15:00');
862
expect((int) Engine::player($g2, 'a')['ap'] === $apA + 1, 'AP granted at 15:00');
863
// A tick just before 15:00 must not grant.
864
$g3 = Engine::applyDue($g, Engine::nextDistribution($t15, '15:00') - 1);
865
expect((int) $g3['day'] === 0, 'one second before 15:00: no grant');
866
867
echo "Engine: AP loot default off; on only for eliminating shots\n";
868
[$g, $t] = visGame(['ap_loot' => false], $now);
869
foreach ($g['players'] as $i => $p) {
870
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 1; $g['players'][$i]['ap'] = 4; }
871
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }
872
}
873
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
874
$a = Engine::player($g, 'a');
875
$b = Engine::player($g, 'b');
876
expect(empty($b['alive']), 'B is dead');
877
expect((int) $b['ap'] === 0, 'dead B has 0 AP');
878
expect((int) $a['ap'] === 2, 'loot off: A spent 1, did not receive B’s 4 (has 2)');
879
$shoot = null;
880
foreach ($g['events'] as $e) { if (($e['type'] ?? '') === 'shoot' && !empty($e['killed'])) { $shoot = $e; } }
881
expect(!isset($shoot['loot']), 'loot off: no loot field on the kill shot');
882
883
[$g, $t] = visGame(['ap_loot' => true], $now);
884
foreach ($g['players'] as $i => $p) {
885
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 1; $g['players'][$i]['ap'] = 4; }
886
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }
887
}
888
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
889
$a = Engine::player($g, 'a');
890
$b = Engine::player($g, 'b');
891
expect(empty($b['alive']) && (int) $b['ap'] === 0, 'loot on: B dead, AP zeroed');
892
expect((int) $a['ap'] === 2 + 4, 'loot on: A spent 1 (3→2) then looted 4 → 6: ' . $a['ap']);
893
$va = Engine::present($g, 'a', $t);
894
$vc = Engine::present($g, 'c', $t);
895
$sa = visEvents($va, 'shoot')[0] ?? [];
896
$sc = visEvents($vc, 'shoot')[0] ?? [];
897
expect(($sa['loot'] ?? 0) === 4, 'shooter sees loot amount');
898
expect(($sc['loot'] ?? 0) === 4, 'public AP: third party sees loot');
899
900
// Hidden AP: third party does not see loot amount; shooter does.
901
[$g, $t] = visGame(['ap_loot' => true, 'vis_ap' => 'hidden'], $now);
902
foreach ($g['players'] as $i => $p) {
903
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 1; $g['players'][$i]['ap'] = 4; }
904
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }
905
}
906
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
907
$va = Engine::present($g, 'a', $t);
908
$vc = Engine::present($g, 'c', $t);
909
expect((visEvents($va, 'shoot')[0]['loot'] ?? 0) === 4, 'shooter sees loot even if AP totals hidden');
910
expect(!array_key_exists('loot', visEvents($vc, 'shoot')[0]), 'third party does not see loot amount when AP is hidden');
911
expect(visPlayer($va, 'a')['ap'] === 6, 'shooter sees own AP including loot');
912
expect(visPlayer($vc, 'a')['ap'] === null, 'third party still does not see A’s total');
913
914
// Non-elim shot does not loot; surrender does not loot A’s AP to anyone.
915
[$g, $t] = visGame(['ap_loot' => true], $now);
916
foreach ($g['players'] as $i => $p) {
917
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 3; $g['players'][$i]['ap'] = 4; }
918
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }
919
}
920
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);
921
expect((int) Engine::player($g, 'a')['ap'] === 2, 'non-elim: no loot');
922
expect((int) Engine::player($g, 'b')['ap'] === 4, 'non-elim: B keeps AP');
923
$g = Engine::applyAction($g, 'b', ['type' => 'surrender'], $t);
924
expect(empty(Engine::player($g, 'b')['alive']), 'B surrendered');
925
expect((int) Engine::player($g, 'a')['ap'] === 2, 'surrender does not transfer AP');
926
expect((int) Engine::player($g, 'b')['ap'] === 0, 'surrendered AP is zeroed, not looted');
927
928
echo "Engine: no hearts, no buying lives (options do not exist)\n";
929
$n = Engine::normalizeRules(['hearts' => true, 'buy_lives' => true, 'buyLives' => true]);
930
expect(!array_key_exists('hearts', $n) && !array_key_exists('buy_lives', $n) && !array_key_exists('buyLives', $n),
931
'hearts / buy-lives are not accepted rule keys');
932
933
934
echo "\nEngine passed: $passed Failed: $failed\n";
935
if (!defined('ALLIANTIES_TEST_SUITE')) {
936
exit($failed > 0 ? 1 : 0);
937
}
938
$GLOBALS['engine_failed'] = $failed;
939
$GLOBALS['engine_passed'] = $passed;
@@ -0,0 +1,939 @@1
<?php2
declare(strict_types=1);3
require_once dirname(__DIR__) . '/lib/Engine.php';4
5
$failed = 0;6
$passed = 0;7
8
function expect(bool $cond, string $msg): void9
{10
global $failed, $passed;11
if ($cond) {12
$passed++;13
echo " ok $msg\n";14
} else {15
$failed++;16
echo " FAIL $msg\n";17
}18
}19
20
function game(array $ids, array $rules = [], ?int $now = null): array21
{22
$now = $now ?? 1_700_000_000; // 2023-11-14 22:13:20 UTC — a mid-evening23
$g = Engine::newLobby('g1', 'ABC234', $ids[0], $ids[0], null, $rules, $now);24
for ($i = 1; $i < count($ids); $i++) {25
$g = Engine::join($g, $ids[$i], $ids[$i], null, $now);26
}27
$g = Engine::start($g, $ids[0], $now);28
return $g;29
}30
31
echo "Engine: grid and placement\n";32
expect(Engine::gridSize(2) === 6, '2 players → 6×6');33
expect(Engine::gridSize(4) === 6, '4 players → 6×6');34
expect(Engine::gridSize(8) === 7, '8 players → 7×7 (ceil sqrt(48)=7)');35
expect(Engine::gridSize(12) === 9, '12 players → 9×9 (ceil sqrt(72)=9)');36
expect(Engine::maxInset(6) === 1, '6×6 max inset 1 (leaves 4×4, min arena 3)');37
expect(Engine::maxInset(7) === 2, '7×7 max inset 2 (leaves 3×3)');38
$pos = Engine::startingPositions(4, 6);39
expect(count($pos) === 4, '4 starting positions');40
$keys = array_map(fn ($p) => $p['x'] . ',' . $p['y'], $pos);41
expect(count(array_unique($keys)) === 4, 'starting positions are unique');42
foreach ($pos as $p) {43
expect(Engine::inBounds(6, $p['x'], $p['y']), "start in bounds {$p['x']},{$p['y']}");44
}45
46
echo "Engine: Chebyshev range\n";47
expect(Engine::chebyshev(0, 0, 2, 2) === 2, 'diagonal 2 is range 2');48
expect(Engine::chebyshev(0, 0, 2, 0) === 2, 'orthogonal 2 is range 2');49
expect(Engine::chebyshev(5, 5, 5, 5) === 0, 'same tile is 0');50
51
echo "Engine: midnight Amsterdam\n";52
// 2026-11-13 23:00 CET = 2026-11-13 22:00 UTC = 1763071200? Let's compute.53
$tz = new DateTimeZone('Europe/Amsterdam');54
$dt = new DateTime('2026-11-13 23:30:00', $tz);55
$from = $dt->getTimestamp();56
$next = Engine::nextMidnight($from);57
$nx = (new DateTime('@' . $next))->setTimezone($tz);58
expect($nx->format('Y-m-d H:i:s') === '2026-11-14 00:00:00', 'next midnight after 23:30 is 00:00 next day: ' . $nx->format('Y-m-d H:i:s'));59
$dt2 = new DateTime('2026-11-14 00:00:00', $tz);60
$next2 = Engine::nextMidnight($dt2->getTimestamp());61
$nx2 = (new DateTime('@' . $next2))->setTimezone($tz);62
expect($nx2->format('Y-m-d H:i:s') === '2026-11-15 00:00:00', 'at exactly 00:00, next is tomorrow');63
// DST spring-forward 2026-03-29 in NL64
$dt3 = new DateTime('2026-03-28 23:00:00', $tz);65
$next3 = Engine::nextMidnight($dt3->getTimestamp());66
$nx3 = (new DateTime('@' . $next3))->setTimezone($tz);67
expect($nx3->format('Y-m-d H:i:s') === '2026-03-29 00:00:00', 'DST: next midnight still 00:00: ' . $nx3->format('Y-m-d H:i:s'));68
69
echo "Engine: lobby and start\n";70
$now = (new DateTime('2026-11-13 15:00:00', $tz))->getTimestamp();71
$g = Engine::newLobby('g', 'CODE12', 'a', 'Alice', null, [], $now);72
expect($g['status'] === 'lobby', 'new lobby');73
expect($g['rules']['jury'] === true, 'jury default ON');74
expect($g['rules']['shrinking_arena'] === false, 'shrink default OFF');75
expect($g['rules']['shrink_interval_days'] === 7, 'shrink interval default 7');76
expect($g['rules']['ceasefire'] === false, 'ceasefire default OFF');77
expect($g['rules']['ceasefire_ranges'] === [], 'ceasefire ranges empty by default');78
expect($g['rules']['vis_shots'] === 'public', 'vis_shots default public');79
expect($g['rules']['vis_gifts'] === 'public', 'vis_gifts default public');80
expect($g['rules']['vis_ap'] === 'public', 'vis_ap default public');81
expect($g['rules']['vis_range'] === 'public', 'vis_range default public');82
expect($g['rules']['vis_lives'] === 'public', 'vis_lives default public');83
expect($g['rules']['ap_loot'] === false, 'ap_loot default OFF');84
expect($g['rules']['ap_time'] === '00:00', 'ap_time default 00:00');85
expect($g['host_id'] === 'a', 'host is creator');86
try {87
Engine::start($g, 'a', $now);88
expect(false, 'start alone should throw');89
} catch (RuntimeException $e) {90
expect($e->getMessage() === 'min_players', 'start alone: min_players');91
}92
$g = Engine::join($g, 'b', 'Bob', null, $now);93
expect(count($g['players']) === 2, '2 players');94
try {95
Engine::start($g, 'b', $now);96
expect(false, 'non-host start');97
} catch (RuntimeException $e) {98
expect($e->getMessage() === 'not_host', 'non-host cannot start');99
}100
$g = Engine::start($g, 'a', $now);101
expect($g['status'] === 'running', 'started');102
expect($g['grid'] === 6, 'grid 6');103
expect($g['players'][0]['ap'] === 1, 'start with 1 AP');104
expect($g['players'][0]['lives'] === 3, 'start with 3 lives');105
expect($g['players'][0]['range'] === 2, 'start with range 2');106
expect($g['players'][0]['x'] !== $g['players'][1]['x'] || $g['players'][0]['y'] !== $g['players'][1]['y'], 'not overlapping');107
$nd = (new DateTime('@' . $g['next_distribution_at']))->setTimezone($tz);108
expect($nd->format('Y-m-d H:i:s') === '2026-11-14 00:00:00', 'next AP at next midnight: ' . $nd->format('Y-m-d H:i:s'));109
110
echo "Engine: move, blocked, AP\n";111
$a = $g['players'][0];112
$legal = Engine::legal($g, 'a');113
expect(count($legal['move']) >= 1, 'Alice has at least one move');114
$t = $legal['move'][0];115
$g2 = Engine::applyAction($g, 'a', ['type' => 'move', 'x' => $t['x'], 'y' => $t['y']], $now);116
expect($g2['players'][0]['x'] === $t['x'] && $g2['players'][0]['y'] === $t['y'], 'moved');117
expect($g2['players'][0]['ap'] === 0, 'spent 1 AP');118
expect(end($g2['events'])['type'] === 'move', 'move event');119
expect(end($g2['events'])['spend'] === true, 'move is a spend tick');120
try {121
Engine::applyAction($g2, 'a', ['type' => 'move', 'x' => $t['x'] + 1, 'y' => $t['y']], $now);122
expect(false, 'move without AP');123
} catch (RuntimeException $e) {124
expect($e->getMessage() === 'no_ap' || $e->getMessage() === 'invalid_move', 'no AP: ' . $e->getMessage());125
}126
127
echo "Engine: shoot and death and win\n";128
// Place two players adjacent, Alice shoots Bob three times (give extra AP).129
$g = game(['a', 'b'], [], $now);130
$g['players'][0]['x'] = 2;131
$g['players'][0]['y'] = 2;132
$g['players'][0]['ap'] = 5;133
$g['players'][1]['x'] = 3;134
$g['players'][1]['y'] = 3;135
$g['players'][1]['ap'] = 0;136
$legal = Engine::legal($g, 'a');137
expect(in_array('b', $legal['shoot'], true), 'Bob is in range 2 (actually dist 1)');138
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);139
expect($g['players'][1]['lives'] === 2, 'Bob has 2 lives');140
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);141
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);142
expect($g['players'][1]['alive'] === false, 'Bob is dead');143
expect($g['status'] === 'finished', 'game finished');144
expect($g['winner_id'] === 'a', 'Alice wins');145
$types = array_column($g['events'], 'type');146
expect(in_array('death', $types, true), 'death event');147
expect(in_array('win', $types, true), 'win event');148
149
echo "Engine: give AP and upgrade\n";150
$g = game(['a', 'b'], [], $now);151
$g['players'][0]['x'] = 2;152
$g['players'][0]['y'] = 2;153
$g['players'][0]['ap'] = 4;154
$g['players'][1]['x'] = 3;155
$g['players'][1]['y'] = 2;156
$g['players'][1]['ap'] = 0;157
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $now);158
expect($g['players'][0]['ap'] === 2, 'Alice spent 2');159
expect($g['players'][1]['ap'] === 2, 'Bob received 2');160
try {161
Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 5], $now);162
expect(false, 'give more than you have');163
} catch (RuntimeException $e) {164
expect($e->getMessage() === 'bad_give', 'bad_give');165
}166
$g = Engine::applyAction($g, 'a', ['type' => 'upgrade'], $now);167
expect($g['players'][0]['range'] === 3, 'range is now 3');168
expect($g['players'][0]['ap'] === 1, 'upgrade costs 1');169
170
echo "Engine: out of range and occupied\n";171
$g = game(['a', 'b'], [], $now);172
$g['players'][0]['x'] = 0;173
$g['players'][0]['y'] = 0;174
$g['players'][0]['ap'] = 2;175
$g['players'][1]['x'] = 5;176
$g['players'][1]['y'] = 5;177
$legal = Engine::legal($g, 'a');178
expect(!in_array('b', $legal['shoot'], true), 'Bob at (5,5) is out of range 2 from (0,0)');179
try {180
Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $now);181
expect(false, 'shoot out of range');182
} catch (RuntimeException $e) {183
expect($e->getMessage() === 'out_of_range', 'out_of_range');184
}185
// Occupied neighbour is not a legal move.186
$g['players'][1]['x'] = 1;187
$g['players'][1]['y'] = 0;188
$legal = Engine::legal($g, 'a');189
$occ = false;190
foreach ($legal['move'] as $m) {191
if ($m['x'] === 1 && $m['y'] === 0) {192
$occ = true;193
}194
}195
expect($occ === false, 'cannot move onto Bob');196
197
echo "Engine: surrender\n";198
$g = game(['a', 'b'], [], $now);199
$g = Engine::applyAction($g, 'b', ['type' => 'surrender'], $now);200
expect($g['players'][1]['alive'] === false, 'Bob surrendered');201
expect($g['players'][1]['surrendered'] === true, 'flagged surrendered');202
expect($g['winner_id'] === 'a', 'Alice wins after surrender');203
204
echo "Engine: daily AP grant\n";205
$g = game(['a', 'b'], ['jury' => false], $now);206
$g['players'][0]['ap'] = 0;207
$g['players'][1]['ap'] = 0;208
$at = $g['next_distribution_at'];209
$g = Engine::applyDue($g, $at);210
expect($g['day'] === 1, 'day is 1');211
expect($g['players'][0]['ap'] === 1, 'Alice got 1 AP');212
expect($g['players'][1]['ap'] === 1, 'Bob got 1 AP');213
// Catch-up two more midnights214
$at2 = Engine::nextMidnight($at);215
$at3 = Engine::nextMidnight($at2);216
$g = Engine::applyDue($g, $at3);217
expect($g['day'] === 3, 'caught up to day 3, day=' . $g['day']);218
expect($g['players'][0]['ap'] === 3, '3 AP after 3 days (started 0): ' . $g['players'][0]['ap']);219
220
echo "Engine: jury\n";221
$g = game(['a', 'b', 'c', 'd'], ['jury' => true, 'shrinking_arena' => false], $now);222
// Kill c and d without ending? Need 4 players, kill only c (one dead voter).223
// Place and shoot c twice then once more... easier: set lives.224
$g['players'][2]['lives'] = 0;225
$g['players'][2]['alive'] = false;226
$g['players'][2]['ap'] = 0;227
$g['players'][3]['lives'] = 0;228
$g['players'][3]['alive'] = false;229
$g['players'][3]['ap'] = 0;230
expect($g['status'] === 'running', 'still running with 2 alive');231
// c votes for a, d votes for a232
$g = Engine::applyAction($g, 'c', ['type' => 'vote', 'target' => 'a'], $now);233
$g = Engine::applyAction($g, 'd', ['type' => 'vote', 'target' => 'a'], $now);234
expect($g['votes']['c'] === 'a', 'c voted a');235
// Vote is changeable236
$g = Engine::applyAction($g, 'd', ['type' => 'vote', 'target' => 'b'], $now);237
expect($g['votes']['d'] === 'b', 'd changed vote to b');238
// Living player cannot vote239
try {240
Engine::applyAction($g, 'a', ['type' => 'vote', 'target' => 'b'], $now);241
expect(false, 'living vote');242
} catch (RuntimeException $e) {243
expect($e->getMessage() === 'cannot_vote', 'living cannot vote');244
}245
// Present hides votes from others246
$viewA = Engine::present($g, 'a');247
expect($viewA['legal']['my_vote'] === null, 'Alice (living) has no vote');248
$viewC = Engine::present($g, 'c');249
expect($viewC['legal']['my_vote'] === 'a', 'Charlie sees own vote');250
expect(!isset($viewA['votes']), 'votes not in present payload');251
// Distribution: 1 vote a, 1 vote b → tie, both get +1 bonus (+1 regular) = +2252
$g['players'][0]['ap'] = 0;253
$g['players'][1]['ap'] = 0;254
$g = Engine::applyDue($g, $g['next_distribution_at']);255
expect($g['players'][0]['ap'] === 2, 'Alice got 1+1 (tie): ' . $g['players'][0]['ap']);256
expect($g['players'][1]['ap'] === 2, 'Bob got 1+1 (tie): ' . $g['players'][1]['ap']);257
expect($g['votes'] === [], 'votes reset after distribution');258
// Unique winner259
$g['players'][2]['alive'] = false;260
$g = Engine::applyAction($g, 'c', ['type' => 'vote', 'target' => 'a'], $now + 1);261
$g = Engine::applyAction($g, 'd', ['type' => 'vote', 'target' => 'a'], $now + 1);262
$g['players'][0]['ap'] = 0;263
$g['players'][1]['ap'] = 0;264
$g = Engine::applyDue($g, $g['next_distribution_at']);265
expect($g['players'][0]['ap'] === 2, 'Alice unique jury winner: 2');266
expect($g['players'][1]['ap'] === 1, 'Bob only regular 1: ' . $g['players'][1]['ap']);267
// Jury off: no vote268
$gOff = game(['a', 'b', 'c'], ['jury' => false], $now);269
$gOff['players'][2]['alive'] = false;270
$gOff['players'][2]['lives'] = 0;271
try {272
Engine::applyAction($gOff, 'c', ['type' => 'vote', 'target' => 'a'], $now);273
expect(false, 'vote with jury off');274
} catch (RuntimeException $e) {275
expect($e->getMessage() === 'cannot_vote', 'jury off: cannot_vote');276
}277
278
echo "Engine: shrinking arena\n";279
$g = game(['a', 'b'], ['shrinking_arena' => true, 'shrink_interval_days' => 2, 'jury' => false], $now);280
expect($g['grid'] === 6, '6×6');281
expect(Engine::daysUntilShrink($g) === 2, 'shrink in 2 days (interval 2, day 0): ' . (Engine::daysUntilShrink($g) ?? 'null'));282
// Put Alice on the outer ring (0,0), Bob in the centre (2,2)283
$g['players'][0]['x'] = 0;284
$g['players'][0]['y'] = 0;285
$g['players'][0]['lives'] = 3;286
$g['players'][0]['ap'] = 0;287
$g['players'][1]['x'] = 2;288
$g['players'][1]['y'] = 2;289
$g['players'][1]['ap'] = 0;290
// Day 1: no shrink291
$g = Engine::applyDue($g, $g['next_distribution_at']);292
expect($g['day'] === 1, 'day 1');293
expect($g['arena_inset'] === 0, 'no shrink on day 1');294
expect($g['players'][0]['x'] === 0 && $g['players'][0]['y'] === 0, 'Alice still on (0,0)');295
expect($g['players'][0]['lives'] === 3, 'Alice still 3 lives');296
expect(Engine::daysUntilShrink($g) === 1, 'shrink in 1 day');297
// Day 2: shrink298
$g = Engine::applyDue($g, $g['next_distribution_at']);299
expect($g['day'] === 2, 'day 2');300
expect($g['arena_inset'] === 1, 'inset is 1');301
expect($g['players'][0]['lives'] === 2, 'Alice lost 1 life: ' . $g['players'][0]['lives']);302
expect(Engine::isPassable(6, 1, $g['players'][0]['x'], $g['players'][0]['y']), 'Alice pushed inward to passable ' . $g['players'][0]['x'] . ',' . $g['players'][0]['y']);303
expect(!($g['players'][0]['x'] === 2 && $g['players'][0]['y'] === 2), 'not onto Bob');304
expect($g['players'][1]['lives'] === 3, 'Bob unhurt in centre');305
expect($g['players'][0]['ap'] === 2, 'Alice got day-1 and day-2 AP after surviving shrink: ' . $g['players'][0]['ap']);306
// Outer ring is impassable307
$legal = Engine::legal($g, $g['players'][0]['id'] === 'a' ? 'a' : 'a');308
foreach ($legal['move'] as $m) {309
expect(Engine::isPassable(6, 1, $m['x'], $m['y']), "legal move {$m['x']},{$m['y']} is passable");310
}311
// Max one shrink on 6×6 (maxInset=1); day 4 would try again but stop312
$g = Engine::applyDue($g, $g['next_distribution_at']); // day 3313
$g = Engine::applyDue($g, $g['next_distribution_at']); // day 4314
expect($g['arena_inset'] === 1, 'does not shrink past max inset: ' . $g['arena_inset']);315
expect(Engine::daysUntilShrink($g) === null, 'no upcoming shrink at max');316
317
echo "Engine: shrink kills and crush and draw\n";318
$g = game(['a', 'b'], ['shrinking_arena' => true, 'shrink_interval_days' => 1, 'jury' => false], $now);319
$g['players'][0]['x'] = 0;320
$g['players'][0]['y'] = 0;321
$g['players'][0]['lives'] = 1;322
$g['players'][1]['x'] = 5;323
$g['players'][1]['y'] = 5;324
$g['players'][1]['lives'] = 1;325
$g = Engine::applyDue($g, $g['next_distribution_at']);326
expect($g['players'][0]['alive'] === false, 'Alice died on shrink (1 life)');327
expect($g['players'][1]['alive'] === false, 'Bob died on shrink (1 life)');328
expect($g['status'] === 'finished', 'finished');329
expect($g['draw'] === true, 'draw when both die in the same shrink');330
331
echo "Engine: notes and chat privacy\n";332
$g = game(['a', 'b'], [], $now);333
$g = Engine::setNote($g, 'a', 'b', 'looks dangerous');334
$viewA = Engine::present($g, 'a');335
$viewB = Engine::present($g, 'b');336
$noteAonB = null;337
$noteBonB = null;338
foreach ($viewA['players'] as $p) {339
if ($p['id'] === 'b') {340
$noteAonB = $p['note'];341
}342
}343
foreach ($viewB['players'] as $p) {344
if ($p['id'] === 'b') {345
$noteBonB = $p['note'];346
}347
}348
expect($noteAonB === 'looks dangerous', 'Alice sees her note on Bob');349
expect($noteBonB === '', 'Bob does not see Alice’s note');350
$g = Engine::addMessage($g, 'a', 'b', 'hello', $now);351
$viewA = Engine::present($g, 'a');352
$viewB = Engine::present($g, 'b');353
expect(count($viewA['messages']) === 1 && $viewA['messages'][0]['text'] === 'hello', 'Alice sees chat');354
expect(count($viewB['messages']) === 1, 'Bob sees chat');355
// A third player would not — add c in lobby... already started. Fine.356
357
echo "Engine: modular rule flags\n";358
$r = Engine::normalizeRules(['jury' => '0', 'shrinking_arena' => '1', 'shrink_interval_days' => 99, 'ceasefire' => '1']);359
expect($r['jury'] === false, 'jury "0" is false');360
expect($r['shrinking_arena'] === true, 'shrink "1" is true');361
expect($r['shrink_interval_days'] === 30, 'interval clamped to max 30: ' . $r['shrink_interval_days']);362
expect($r['ceasefire'] === true, 'ceasefire "1" is true');363
364
echo "Engine: cease-fire ranges and midnight wrap\n";365
$ranges = Engine::normalizeRanges([366
['start' => '22:00', 'end' => '06:00'],367
['start' => '12:00', 'end' => '13:30'],368
['start' => '25:00', 'end' => '01:00'], // invalid369
['start' => '08:00', 'end' => '08:00'], // zero-length dropped370
]);371
expect(count($ranges) === 2, '2 valid ranges: ' . count($ranges));372
expect($ranges[0]['start'] === '12:00', 'sorted, first is 12:00');373
expect($ranges[1]['start'] === '22:00', 'wrap range kept');374
375
$g = game(['a', 'b'], [376
'jury' => false,377
'ceasefire' => true,378
'ceasefire_ranges' => [379
['start' => '22:00', 'end' => '06:00'],380
['start' => '12:00', 'end' => '13:00'],381
],382
], $now);383
// Place adjacent so shoot would otherwise be legal.384
$g['players'][0]['x'] = 2;385
$g['players'][0]['y'] = 2;386
$g['players'][0]['ap'] = 3;387
$g['players'][1]['x'] = 3;388
$g['players'][1]['y'] = 2;389
390
// 2026-11-13 23:30 Amsterdam — inside 22:00-06:00 wrap391
$inCf = (new DateTime('2026-11-13 23:30:00', $tz))->getTimestamp();392
$info = Engine::ceasefireInfo($g, $inCf);393
expect($info !== null && $info['active'] === true, '23:30 is cease-fire (wrap)');394
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);395
expect($end->format('Y-m-d H:i') === '2026-11-14 06:00', 'ends at 06:00 next day: ' . $end->format('Y-m-d H:i'));396
$legal = Engine::legal($g, 'a', $inCf);397
expect($legal['shoot'] === [], 'Attack disabled during cease-fire');398
expect($legal['ceasefire'] === true, 'legal.ceasefire true');399
expect(count($legal['move']) >= 1 || $legal['upgrade'] || true, 'non-shoot actions still considered');400
// Move is still allowed401
$legalMove = $legal['move'];402
expect(!empty($legalMove), 'can still move during cease-fire');403
try {404
Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $inCf);405
expect(false, 'shoot during cease-fire should throw');406
} catch (RuntimeException $e) {407
expect($e->getMessage() === 'ceasefire', 'error code ceasefire: ' . $e->getMessage());408
}409
410
// 2026-11-14 06:00 exactly — end is exclusive, so not active411
$atEnd = (new DateTime('2026-11-14 06:00:00', $tz))->getTimestamp();412
$info = Engine::ceasefireInfo($g, $atEnd);413
expect($info['active'] === false, '06:00 exactly is not cease-fire (end exclusive)');414
$until = (new DateTime('@' . $info['until']))->setTimezone($tz);415
expect($until->format('H:i') === '12:00', 'next cease-fire at 12:00: ' . $until->format('H:i'));416
417
// 12:30 — second range418
$noon = (new DateTime('2026-11-14 12:30:00', $tz))->getTimestamp();419
$info = Engine::ceasefireInfo($g, $noon);420
expect($info['active'] === true, '12:30 is cease-fire');421
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);422
expect($end->format('H:i') === '13:00', 'ends 13:00: ' . $end->format('H:i'));423
424
// 15:00 — free, next is 22:00 same day425
$afternoon = (new DateTime('2026-11-14 15:00:00', $tz))->getTimestamp();426
$info = Engine::ceasefireInfo($g, $afternoon);427
expect($info['active'] === false, '15:00 is free');428
$until = (new DateTime('@' . $info['until']))->setTimezone($tz);429
expect($until->format('Y-m-d H:i') === '2026-11-14 22:00', 'until 22:00: ' . $until->format('Y-m-d H:i'));430
$legal = Engine::legal($g, 'a', $afternoon);431
expect(in_array('b', $legal['shoot'], true), 'can shoot when not in cease-fire');432
$g2 = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $afternoon);433
expect($g2['players'][1]['lives'] === 2, 'shot landed outside cease-fire');434
435
// Just before midnight wrap: 21:59 — until 22:00436
$before = (new DateTime('2026-11-14 21:59:00', $tz))->getTimestamp();437
$info = Engine::ceasefireInfo($g, $before);438
expect($info['active'] === false, '21:59 is free');439
expect($info['seconds'] === 60, '60 seconds until cease-fire: ' . $info['seconds']);440
441
// 05:59 next morning: 60 seconds left IN cease-fire442
$late = (new DateTime('2026-11-15 05:59:00', $tz))->getTimestamp();443
$info = Engine::ceasefireInfo($g, $late);444
expect($info['active'] === true, '05:59 still cease-fire');445
expect($info['seconds'] === 60, '60 seconds left in cease-fire: ' . $info['seconds']);446
447
echo "Engine: cease-fire DST spring-forward (2026-03-29 02:00→03:00)\n";448
// Range 01:00-04:00 on spring-forward day: 02:00 does not exist, period is 2 hours of real time.449
$gD = game(['a', 'b'], [450
'ceasefire' => true,451
'ceasefire_ranges' => [['start' => '01:00', 'end' => '04:00']],452
'jury' => false,453
], $now);454
$start = (new DateTime('2026-03-29 01:00:00', $tz))->getTimestamp();455
$info = Engine::ceasefireInfo($gD, $start);456
expect($info['active'] === true, '01:00 CEST-transition day is cease-fire');457
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);458
expect($end->format('Y-m-d H:i') === '2026-03-29 04:00', 'ends 04:00: ' . $end->format('Y-m-d H:i'));459
// Real duration should be 2 hours (01:00 CET + skipped 02:00 hour → 04:00 CEST)460
// 01:00 on that day is still CET (UTC+1), 04:00 is CEST (UTC+2).461
$dur = $info['until'] - $start;462
expect($dur === 2 * 3600, 'spring-forward 01:00-04:00 is 2 real hours: ' . $dur);463
// 02:30 does not exist; 03:00 should still be inside464
$three = (new DateTime('2026-03-29 03:00:00', $tz))->getTimestamp();465
$info = Engine::ceasefireInfo($gD, $three);466
expect($info['active'] === true, '03:00 (after the jump) is still cease-fire');467
expect($info['seconds'] === 3600, '1 hour left at 03:00: ' . $info['seconds']);468
// Before: 00:30, until 01:00 = 30 min469
$half = (new DateTime('2026-03-29 00:30:00', $tz))->getTimestamp();470
$info = Engine::ceasefireInfo($gD, $half);471
expect($info['active'] === false, '00:30 is free');472
expect($info['seconds'] === 1800, '30 min until 01:00: ' . $info['seconds']);473
474
echo "Engine: cease-fire DST fall-back (2026-10-25 03:00→02:00)\n";475
// Range 01:00-03:30. The 02:00 hour happens twice. amsterdamWallclock adds minutes476
// from midnight, so 03:30 is unambiguous (after the fallback). Duration:477
// midnight CEST 00:00 = UTC 22:00 previous; +3.5h = 03:30 CET? Let's assert via DateTime.478
$gF = game(['a', 'b'], [479
'ceasefire' => true,480
'ceasefire_ranges' => [['start' => '01:00', 'end' => '03:30']],481
'jury' => false,482
], $now);483
$fbStart = (new DateTime('2026-10-25 01:00:00', $tz))->getTimestamp();484
$info = Engine::ceasefireInfo($gF, $fbStart);485
expect($info['active'] === true, '01:00 fall-back day is cease-fire');486
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);487
expect($end->format('Y-m-d H:i') === '2026-10-25 03:30', 'ends 03:30: ' . $end->format('Y-m-d H:i'));488
$dur = $info['until'] - $fbStart;489
// 01:00 CEST (UTC 23:00) to 03:30 CET (UTC 02:30) = 3.5 hours (the 02:00 hour repeats).490
expect($dur === (int) (3.5 * 3600), 'fall-back 01:00-03:30 is 3.5 real hours: ' . $dur);491
// A moment during the repeated 02:xx should still be active.492
// 02:15 CEST (first) = 01:00 CEST + 75 min.493
$first215 = $fbStart + 75 * 60;494
$info = Engine::ceasefireInfo($gF, $first215);495
expect($info['active'] === true, 'first 02:15 (still DST) is cease-fire');496
// 02:15 CET (second) = 01:00 + 75 min + 60 min (the repeated hour)497
$second215 = $fbStart + (75 + 60) * 60;498
$info = Engine::ceasefireInfo($gF, $second215);499
expect($info['active'] === true, 'second 02:15 (CET) is still cease-fire');500
// After 03:30 CET: free501
$after = (new DateTime('2026-10-25 03:30:00', $tz))->getTimestamp();502
$info = Engine::ceasefireInfo($gF, $after);503
expect($info['active'] === false, '03:30 exactly is free (end exclusive)');504
505
echo "Engine: cease-fire off or empty ranges\n";506
$gN = game(['a', 'b'], ['ceasefire' => false, 'ceasefire_ranges' => [['start' => '00:00', 'end' => '23:59']]], $now);507
expect(Engine::ceasefireInfo($gN, $now) === null, 'rule off → no info (ranges ignored)');508
$gE = game(['a', 'b'], ['ceasefire' => true, 'ceasefire_ranges' => []], $now);509
expect(Engine::ceasefireInfo($gE, $now) === null, 'on but empty ranges → treated as no cease-fire');510
511
echo "Engine: overlapping ranges merge for countdown\n";512
$gM = game(['a', 'b'], [513
'ceasefire' => true,514
'ceasefire_ranges' => [515
['start' => '10:00', 'end' => '12:00'],516
['start' => '11:00', 'end' => '13:00'],517
],518
'jury' => false,519
], $now);520
$t = (new DateTime('2026-11-14 10:30:00', $tz))->getTimestamp();521
$info = Engine::ceasefireInfo($gM, $t);522
$end = (new DateTime('@' . $info['until']))->setTimezone($tz);523
expect($end->format('H:i') === '13:00', 'merged overlapping ends at 13:00: ' . $end->format('H:i'));524
525
526
echo "Engine: visibility defaults and invalid values fall back to public\n";527
$norm = Engine::normalizeRules([528
'vis_shots' => 'nope',529
'vis_gifts' => 123,530
'vis_ap' => 'PUBLIC',531
'vis_range' => '',532
'vis_lives' => null,533
]);534
expect($norm['vis_shots'] === 'public', 'bad vis_shots → public');535
expect($norm['vis_gifts'] === 'public', 'bad vis_gifts → public');536
expect($norm['vis_ap'] === 'public', 'bad vis_ap → public');537
expect($norm['vis_range'] === 'public', 'bad vis_range → public');538
expect($norm['vis_lives'] === 'public', 'bad vis_lives → public');539
$ok = Engine::normalizeRules([540
'vis_shots' => 'elim_known_target',541
'vis_gifts' => 'anonymous',542
'vis_ap' => 'hidden',543
'vis_range' => 'known_in_range',544
'vis_lives' => 'hidden',545
]);546
expect($ok['vis_shots'] === 'elim_known_target', 'accepts elim_known_target');547
expect($ok['vis_gifts'] === 'anonymous', 'accepts anonymous');548
expect($ok['vis_ap'] === 'hidden', 'accepts hidden AP');549
expect($ok['vis_range'] === 'known_in_range', 'accepts known_in_range');550
expect($ok['vis_lives'] === 'hidden', 'accepts hidden lives');551
552
/**553
* Three-player game with A next to B (in starting range 2) and C far away.554
* Extra AP so we can shoot/give/upgrade more than once.555
*556
* @return array{0:array,1:int}557
*/558
function visGame(array $vis, int $now): array559
{560
$g = game(['a', 'b', 'c'], array_merge(['jury' => false], $vis), $now);561
// Place: A at (2,2), B at (3,2) dist 1, C at (5,5) dist 3 from A.562
foreach ($g['players'] as $i => $p) {563
if ($p['id'] === 'a') {564
$g['players'][$i]['x'] = 2;565
$g['players'][$i]['y'] = 2;566
$g['players'][$i]['ap'] = 5;567
$g['players'][$i]['range'] = 2;568
} elseif ($p['id'] === 'b') {569
$g['players'][$i]['x'] = 3;570
$g['players'][$i]['y'] = 2;571
$g['players'][$i]['ap'] = 5;572
$g['players'][$i]['range'] = 2;573
} else {574
$g['players'][$i]['x'] = 5;575
$g['players'][$i]['y'] = 5;576
$g['players'][$i]['ap'] = 5;577
$g['players'][$i]['range'] = 2;578
}579
}580
return [$g, $now];581
}582
583
function visEvents(array $view, string $type): array584
{585
return array_values(array_filter($view['events'] ?? [], fn ($e) => ($e['type'] ?? '') === $type));586
}587
588
function visPlayer(array $view, string $id): ?array589
{590
foreach ($view['players'] as $p) {591
if ($p['id'] === $id) {592
return $p;593
}594
}595
return null;596
}597
598
echo "Engine: vis shots — public (everyone sees, including lives_left when lives public)\n";599
[$g, $t] = visGame(['vis_shots' => 'public'], $now);600
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);601
$va = Engine::present($g, 'a', $t);602
$vb = Engine::present($g, 'b', $t);603
$vc = Engine::present($g, 'c', $t);604
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees public shot');605
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees public shot');606
expect(count(visEvents($vc, 'shoot')) === 1, 'third party sees public shot');607
expect(($vc['events'] === visEvents($vc, 'shoot') ? true : isset(visEvents($vc, 'shoot')[0]['player'])) && visEvents($vc, 'shoot')[0]['player'] === 'a', 'third party sees shooter id');608
expect(visEvents($vc, 'shoot')[0]['lives_left'] === 2, 'public lives_left on shot');609
expect(visEvents($vc, 'shoot')[0]['damage'] === 1, 'damage is 1');610
expect(visPlayer($vc, 'b')['lives'] === 2, 'public lives in state');611
612
echo "Engine: vis shots — elim_public (non-elim hidden from third party, visible to target)\n";613
[$g, $t] = visGame(['vis_shots' => 'elim_public'], $now);614
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);615
$va = Engine::present($g, 'a', $t);616
$vb = Engine::present($g, 'b', $t);617
$vc = Engine::present($g, 'c', $t);618
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees non-elim');619
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees non-elim under elim_public');620
expect(count(visEvents($vc, 'shoot')) === 0, 'third party does not see non-elim');621
expect(count(visEvents($vc, 'death')) === 0, 'no death on non-elim');622
// Two more shots to eliminate (B started with 3, now 2).623
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);624
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);625
$vc = Engine::present($g, 'c', $t);626
$vb = Engine::present($g, 'b', $t);627
$shotsC = visEvents($vc, 'shoot');628
expect(count($shotsC) === 1, 'third party sees only the eliminating shot: ' . count($shotsC));629
expect(!empty($shotsC[0]['killed']), 'the visible shot is the kill');630
expect(count(visEvents($vc, 'death')) === 1, 'third party sees death');631
expect((visEvents($vc, 'death')[0]['by'] ?? null) === 'a', 'elim_public death includes killer');632
expect((visEvents($vb, 'death')[0]['by'] ?? null) === 'a', 'target sees killer');633
expect(visPlayer($vc, 'b')['alive'] === false, 'death/alive is always public');634
635
echo "Engine: vis shots — known_target (others never see the shot, death without by)\n";636
[$g, $t] = visGame(['vis_shots' => 'known_target'], $now);637
$g['players'][array_key_first(array_filter($g['players'], fn ($p) => $p['id'] === 'b'))]['lives'] = 1;638
// find b index properly639
foreach ($g['players'] as $i => $p) {640
if ($p['id'] === 'b') {641
$g['players'][$i]['lives'] = 1;642
}643
}644
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);645
$va = Engine::present($g, 'a', $t);646
$vb = Engine::present($g, 'b', $t);647
$vc = Engine::present($g, 'c', $t);648
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees known_target shot');649
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees known_target shot');650
expect(count(visEvents($vc, 'shoot')) === 0, 'third party does not see known_target shot');651
$deaths = visEvents($vc, 'death');652
expect(count($deaths) === 1, 'third party still sees that B died');653
expect(!array_key_exists('by', $deaths[0]), 'killer stripped for third party under known_target');654
expect((visEvents($vb, 'death')[0]['by'] ?? null) === 'a', 'target still sees who shot them');655
656
echo "Engine: vis shots — elim_known_target (non-elim hidden even from target)\n";657
[$g, $t] = visGame(['vis_shots' => 'elim_known_target'], $now);658
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);659
$va = Engine::present($g, 'a', $t);660
$vb = Engine::present($g, 'b', $t);661
$vc = Engine::present($g, 'c', $t);662
expect(count(visEvents($va, 'shoot')) === 1, 'shooter sees non-elim under elim_known_target');663
expect(count(visEvents($vb, 'shoot')) === 0, 'target does NOT see non-elim shot (must deduce)');664
expect(count(visEvents($vc, 'shoot')) === 0, 'third party does not see non-elim');665
expect(visPlayer($vb, 'b')['lives'] === 2, 'target still sees own lives drop');666
expect(visPlayer($vc, 'b')['lives'] === 2, 'lives still public in this game (default)');667
// Eliminate668
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);669
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);670
$vb = Engine::present($g, 'b', $t);671
$vc = Engine::present($g, 'c', $t);672
expect(count(visEvents($vb, 'shoot')) === 1, 'target sees only the eliminating shot');673
expect((visEvents($vb, 'shoot')[0]['player'] ?? null) === 'a', 'elim shot names the shooter for the target');674
expect(count(visEvents($vc, 'shoot')) === 0, 'third party never sees shots under elim_known_target');675
expect(!array_key_exists('by', visEvents($vc, 'death')[0]), 'third party death has no by');676
677
echo "Engine: vis shots + hidden lives — lives_left stripped except for the target\n";678
[$g, $t] = visGame(['vis_shots' => 'public', 'vis_lives' => 'hidden'], $now);679
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);680
$va = Engine::present($g, 'a', $t);681
$vb = Engine::present($g, 'b', $t);682
$vc = Engine::present($g, 'c', $t);683
expect(!array_key_exists('lives_left', visEvents($va, 'shoot')[0]), 'shooter does not get target lives_left');684
expect((visEvents($vb, 'shoot')[0]['lives_left'] ?? null) === 2, 'target sees own lives_left');685
expect(!array_key_exists('lives_left', visEvents($vc, 'shoot')[0]), 'third party does not get lives_left');686
expect(visEvents($va, 'shoot')[0]['damage'] === 1, 'shooter still sees damage 1');687
expect(visPlayer($va, 'a')['lives'] === 3, 'own lives always visible');688
expect(visPlayer($va, 'b')['lives'] === null, 'other lives hidden from shooter');689
expect(visPlayer($vc, 'b')['lives'] === null, 'other lives hidden from third party');690
expect(visPlayer($vb, 'b')['lives'] === 2, 'target sees own lives');691
expect(is_bool(visPlayer($vc, 'b')['alive']), 'alive flag still present when lives hidden');692
693
echo "Engine: vis gifts — public, known_recipient, anonymous\n";694
[$g, $t] = visGame(['vis_gifts' => 'public'], $now);695
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $t);696
$vc = Engine::present($g, 'c', $t);697
$gives = visEvents($vc, 'give');698
expect(count($gives) === 1 && $gives[0]['player'] === 'a' && $gives[0]['amount'] === 2, 'public gift visible to third party with giver and amount');699
700
[$g, $t] = visGame(['vis_gifts' => 'known_recipient'], $now);701
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $t);702
$va = Engine::present($g, 'a', $t);703
$vb = Engine::present($g, 'b', $t);704
$vc = Engine::present($g, 'c', $t);705
expect(count(visEvents($va, 'give')) === 1 && visEvents($va, 'give')[0]['player'] === 'a', 'giver sees own gift');706
expect(count(visEvents($vb, 'give')) === 1 && visEvents($vb, 'give')[0]['player'] === 'a', 'recipient sees giver');707
expect(count(visEvents($vc, 'give')) === 0, 'third party does not see known_recipient gift');708
709
[$g, $t] = visGame(['vis_gifts' => 'anonymous'], $now);710
$beforeB = Engine::player($g, 'b')['ap'];711
$g = Engine::applyAction($g, 'a', ['type' => 'give', 'target' => 'b', 'amount' => 2], $t);712
$va = Engine::present($g, 'a', $t);713
$vb = Engine::present($g, 'b', $t);714
$vc = Engine::present($g, 'c', $t);715
expect(count(visEvents($va, 'give')) === 1 && visEvents($va, 'give')[0]['player'] === 'a', 'giver sees full anonymous gift in their own log');716
$rec = visEvents($vb, 'give');717
expect(count($rec) === 1, 'recipient sees an anonymous gift event');718
expect(!empty($rec[0]['anonymous']), 'event marked anonymous');719
expect(!array_key_exists('player', $rec[0]), 'giver id stripped for recipient');720
expect(($rec[0]['amount'] ?? 0) === 2, 'recipient sees the AP amount');721
expect(($rec[0]['target'] ?? '') === 'b', 'recipient is named as target');722
expect(count(visEvents($vc, 'give')) === 0, 'third party does not see anonymous gift');723
expect(visPlayer($vb, 'b')['ap'] === $beforeB + 2, 'recipient AP actually increased');724
// Stored (unfiltered) event still has the giver — present() must not mutate.725
$rawGive = null;726
foreach ($g['events'] as $e) {727
if (($e['type'] ?? '') === 'give') {728
$rawGive = $e;729
}730
}731
expect($rawGive !== null && ($rawGive['player'] ?? null) === 'a', 'stored event still has the giver (present does not mutate)');732
expect(!array_key_exists('player', $rec[0]) || $rec[0]['player'] !== 'a' || true, 'sanity');733
expect(($rawGive['player'] ?? null) === 'a' && !array_key_exists('player', $rec[0]), 'clone is independent of stored event');734
735
echo "Engine: vis AP totals hidden\n";736
[$g, $t] = visGame(['vis_ap' => 'hidden'], $now);737
$va = Engine::present($g, 'a', $t);738
$vc = Engine::present($g, 'c', $t);739
expect(visPlayer($va, 'a')['ap'] === 5, 'own AP visible when hidden rule is on');740
expect(visPlayer($va, 'b')['ap'] === null, 'other AP hidden');741
expect(visPlayer($vc, 'a')['ap'] === null, 'third party does not see A’s AP');742
// Daily grants: only the viewer’s own grant is included.743
$midnight = Engine::nextMidnight($t);744
$g = Engine::applyDue($g, $midnight);745
$va = Engine::present($g, 'a', $midnight);746
$dailies = visEvents($va, 'daily');747
expect(count($dailies) === 1, 'daily event present');748
expect(array_keys($dailies[0]['grants']) === ['a'], 'hidden AP: only own grant in daily event: ' . json_encode($dailies[0]['grants']));749
expect(!isset($dailies[0]['jury']['counts']), 'jury vote counts stripped');750
751
echo "Engine: vis range — hidden and known_in_range\n";752
[$g, $t] = visGame(['vis_range' => 'hidden'], $now);753
$g = Engine::applyAction($g, 'a', ['type' => 'upgrade'], $t);754
$va = Engine::present($g, 'a', $t);755
$vc = Engine::present($g, 'c', $t);756
expect(visPlayer($va, 'a')['range'] === 3, 'own range after upgrade');757
expect(visPlayer($vc, 'a')['range'] === null, 'other range hidden');758
expect(count(visEvents($va, 'upgrade')) === 1, 'upgrader sees own upgrade');759
expect(count(visEvents($vc, 'upgrade')) === 0, 'third party does not see hidden upgrade');760
761
[$g, $t] = visGame(['vis_range' => 'known_in_range'], $now);762
$va = Engine::present($g, 'a', $t);763
$vb = Engine::present($g, 'b', $t);764
$vc = Engine::present($g, 'c', $t);765
// B is at dist 1 from A (range 2) so A is in B’s range and B is in A’s range.766
expect(visPlayer($vb, 'a')['range'] === 2, 'B is within A’s range, sees A’s range');767
expect(visPlayer($va, 'b')['range'] === 2, 'A is within B’s range, sees B’s range');768
expect(visPlayer($vc, 'a')['range'] === null, 'C is outside A’s range (dist 3 > 2)');769
expect(visPlayer($va, 'c')['range'] === null, 'A is outside C’s range (dist 3 > 2)');770
expect(visPlayer($vc, 'c')['range'] === 2, 'C always sees own range');771
// Upgrade A to range 3: C (dist 3) is now in A’s range.772
$g = Engine::applyAction($g, 'a', ['type' => 'upgrade'], $t);773
$vc = Engine::present($g, 'c', $t);774
$va = Engine::present($g, 'a', $t);775
expect(visPlayer($vc, 'a')['range'] === 3, 'after upgrade, C is within A’s range and sees it');776
expect(count(visEvents($vc, 'upgrade')) === 1, 'C now also sees the upgrade event');777
expect(visPlayer($va, 'c')['range'] === null, 'A is still outside C’s range 2');778
779
echo "Engine: movement is always public, even with everything hidden\n";780
[$g, $t] = visGame([781
'vis_shots' => 'elim_known_target',782
'vis_gifts' => 'anonymous',783
'vis_ap' => 'hidden',784
'vis_range' => 'hidden',785
'vis_lives' => 'hidden',786
], $now);787
// A moves to (2,3) — adjacent empty.788
$g = Engine::applyAction($g, 'a', ['type' => 'move', 'x' => 2, 'y' => 3], $t);789
$vc = Engine::present($g, 'c', $t);790
$moves = visEvents($vc, 'move');791
expect(count($moves) === 1, 'move is public');792
expect($moves[0]['player'] === 'a' && $moves[0]['to']['x'] === 2 && $moves[0]['to']['y'] === 3, 'move names the player and destination');793
expect(visPlayer($vc, 'a')['x'] === 2 && visPlayer($vc, 'a')['y'] === 3, 'new position is in the public state');794
expect(visPlayer($vc, 'a')['ap'] === null, 'AP still hidden after the move');795
expect(visPlayer($vc, 'a')['lives'] === null, 'lives still hidden');796
expect(visPlayer($vc, 'a')['range'] === null, 'range still hidden');797
798
echo "Engine: present() does not leak hidden keys with real values\n";799
[$g, $t] = visGame(['vis_ap' => 'hidden', 'vis_lives' => 'hidden', 'vis_range' => 'hidden'], $now);800
$vc = Engine::present($g, 'c', $t);801
$encoded = json_encode($vc);802
expect(visPlayer($vc, 'a')['ap'] === null, 'JSON-facing ap is null');803
expect(visPlayer($vc, 'a')['lives'] === null, 'JSON-facing lives is null');804
expect(visPlayer($vc, 'a')['range'] === null, 'JSON-facing range is null');805
// The raw numbers for A (ap=5, lives=3, range=2) must not appear attached to A in a leaky way806
// — we only require the structured fields are null, which json_encode will emit as null.807
$decoded = json_decode($encoded, true);808
foreach ($decoded['players'] as $p) {809
if ($p['id'] !== 'c') {810
expect($p['ap'] === null && $p['lives'] === null && $p['range'] === null, "no numeric secrets for {$p['id']}");811
}812
}813
814
815
816
echo "Engine: nextDistribution (per-lobby AP time) and DST\n";817
$tz = new DateTimeZone('Europe/Amsterdam');818
$from = (new DateTime('2026-11-14 14:00:00', $tz))->getTimestamp();819
$nx = Engine::nextDistribution($from, '15:00');820
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');821
expect($got === '2026-11-14 15:00:00', "14:00 → today 15:00: $got");822
$at = (new DateTime('2026-11-14 15:00:00', $tz))->getTimestamp();823
$nx = Engine::nextDistribution($at, '15:00');824
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');825
expect($got === '2026-11-15 15:00:00', "exactly 15:00 → tomorrow 15:00: $got");826
$from2 = (new DateTime('2026-11-14 16:00:00', $tz))->getTimestamp();827
$nx = Engine::nextDistribution($from2, '15:00');828
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');829
expect($got === '2026-11-15 15:00:00', "16:00 → tomorrow 15:00: $got");830
// 00:00 matches nextMidnight831
$eve = (new DateTime('2026-11-13 23:30:00', $tz))->getTimestamp();832
expect(Engine::nextDistribution($eve, '00:00') === Engine::nextMidnight($eve), '00:00 path equals nextMidnight');833
expect(Engine::normalizeRules(['ap_time' => '7:05'])['ap_time'] === '07:05', 'ap_time normalised to HH:MM');834
expect(Engine::normalizeRules(['ap_time' => 'nope'])['ap_time'] === '00:00', 'bad ap_time → 00:00');835
expect(Engine::normalizeRules(['ap_time' => '24:00'])['ap_time'] === '00:00', '24:00 invalid → 00:00');836
837
// DST spring-forward 2026-03-29 02:00–03:00 skipped.838
$before = (new DateTime('2026-03-29 01:30:00', $tz))->getTimestamp();839
$nx = Engine::nextDistribution($before, '02:30');840
$gotDt = (new DateTime('@' . $nx))->setTimezone($tz);841
// 02:30 does not exist; PHP setTime lands on or after the gap (03:30 CEST typically).842
expect($gotDt->getTimestamp() > $before, 'DST spring: 02:30 candidate is strictly after 01:30');843
expect($gotDt->format('Y-m-d') === '2026-03-29', 'DST spring: still that calendar day: ' . $gotDt->format('Y-m-d H:i:s T'));844
// A legal time after the gap is exact.845
$nx = Engine::nextDistribution($before, '04:00');846
$got = (new DateTime('@' . $nx))->setTimezone($tz)->format('Y-m-d H:i:s');847
expect($got === '2026-03-29 04:00:00', "DST spring: 04:00 exact: $got");848
// Fall-back 2026-10-25: 02:30 exists twice; we just need a valid instant that day after 01:30.849
$fb = (new DateTime('2026-10-25 01:30:00', $tz))->getTimestamp();850
$nx = Engine::nextDistribution($fb, '02:30');851
$gotDt = (new DateTime('@' . $nx))->setTimezone($tz);852
expect($gotDt->format('Y-m-d') === '2026-10-25' && (int) $gotDt->format('H') === 2 && (int) $gotDt->format('i') === 30,853
'DST fall-back: 02:30 that day: ' . $gotDt->format('Y-m-d H:i:s T'));854
855
echo "Engine: AP at a non-midnight lobby time\n";856
$t15 = (new DateTime('2026-11-14 14:00:00', $tz))->getTimestamp();857
$g = game(['a', 'b'], ['ap_time' => '15:00', 'jury' => false], $t15);858
expect((int) $g['next_distribution_at'] === Engine::nextDistribution($t15, '15:00'), 'start schedules 15:00');859
$apA = Engine::player($g, 'a')['ap'];860
$g2 = Engine::applyDue($g, Engine::nextDistribution($t15, '15:00'));861
expect((int) $g2['day'] === 1, 'day increments at 15:00');862
expect((int) Engine::player($g2, 'a')['ap'] === $apA + 1, 'AP granted at 15:00');863
// A tick just before 15:00 must not grant.864
$g3 = Engine::applyDue($g, Engine::nextDistribution($t15, '15:00') - 1);865
expect((int) $g3['day'] === 0, 'one second before 15:00: no grant');866
867
echo "Engine: AP loot default off; on only for eliminating shots\n";868
[$g, $t] = visGame(['ap_loot' => false], $now);869
foreach ($g['players'] as $i => $p) {870
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 1; $g['players'][$i]['ap'] = 4; }871
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }872
}873
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);874
$a = Engine::player($g, 'a');875
$b = Engine::player($g, 'b');876
expect(empty($b['alive']), 'B is dead');877
expect((int) $b['ap'] === 0, 'dead B has 0 AP');878
expect((int) $a['ap'] === 2, 'loot off: A spent 1, did not receive B’s 4 (has 2)');879
$shoot = null;880
foreach ($g['events'] as $e) { if (($e['type'] ?? '') === 'shoot' && !empty($e['killed'])) { $shoot = $e; } }881
expect(!isset($shoot['loot']), 'loot off: no loot field on the kill shot');882
883
[$g, $t] = visGame(['ap_loot' => true], $now);884
foreach ($g['players'] as $i => $p) {885
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 1; $g['players'][$i]['ap'] = 4; }886
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }887
}888
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);889
$a = Engine::player($g, 'a');890
$b = Engine::player($g, 'b');891
expect(empty($b['alive']) && (int) $b['ap'] === 0, 'loot on: B dead, AP zeroed');892
expect((int) $a['ap'] === 2 + 4, 'loot on: A spent 1 (3→2) then looted 4 → 6: ' . $a['ap']);893
$va = Engine::present($g, 'a', $t);894
$vc = Engine::present($g, 'c', $t);895
$sa = visEvents($va, 'shoot')[0] ?? [];896
$sc = visEvents($vc, 'shoot')[0] ?? [];897
expect(($sa['loot'] ?? 0) === 4, 'shooter sees loot amount');898
expect(($sc['loot'] ?? 0) === 4, 'public AP: third party sees loot');899
900
// Hidden AP: third party does not see loot amount; shooter does.901
[$g, $t] = visGame(['ap_loot' => true, 'vis_ap' => 'hidden'], $now);902
foreach ($g['players'] as $i => $p) {903
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 1; $g['players'][$i]['ap'] = 4; }904
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }905
}906
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);907
$va = Engine::present($g, 'a', $t);908
$vc = Engine::present($g, 'c', $t);909
expect((visEvents($va, 'shoot')[0]['loot'] ?? 0) === 4, 'shooter sees loot even if AP totals hidden');910
expect(!array_key_exists('loot', visEvents($vc, 'shoot')[0]), 'third party does not see loot amount when AP is hidden');911
expect(visPlayer($va, 'a')['ap'] === 6, 'shooter sees own AP including loot');912
expect(visPlayer($vc, 'a')['ap'] === null, 'third party still does not see A’s total');913
914
// Non-elim shot does not loot; surrender does not loot A’s AP to anyone.915
[$g, $t] = visGame(['ap_loot' => true], $now);916
foreach ($g['players'] as $i => $p) {917
if ($p['id'] === 'b') { $g['players'][$i]['lives'] = 3; $g['players'][$i]['ap'] = 4; }918
if ($p['id'] === 'a') { $g['players'][$i]['ap'] = 3; }919
}920
$g = Engine::applyAction($g, 'a', ['type' => 'shoot', 'target' => 'b'], $t);921
expect((int) Engine::player($g, 'a')['ap'] === 2, 'non-elim: no loot');922
expect((int) Engine::player($g, 'b')['ap'] === 4, 'non-elim: B keeps AP');923
$g = Engine::applyAction($g, 'b', ['type' => 'surrender'], $t);924
expect(empty(Engine::player($g, 'b')['alive']), 'B surrendered');925
expect((int) Engine::player($g, 'a')['ap'] === 2, 'surrender does not transfer AP');926
expect((int) Engine::player($g, 'b')['ap'] === 0, 'surrendered AP is zeroed, not looted');927
928
echo "Engine: no hearts, no buying lives (options do not exist)\n";929
$n = Engine::normalizeRules(['hearts' => true, 'buy_lives' => true, 'buyLives' => true]);930
expect(!array_key_exists('hearts', $n) && !array_key_exists('buy_lives', $n) && !array_key_exists('buyLives', $n),931
'hearts / buy-lives are not accepted rule keys');932
933
934
echo "\nEngine passed: $passed Failed: $failed\n";935
if (!defined('ALLIANTIES_TEST_SUITE')) {936
exit($failed > 0 ? 1 : 0);937
}938
$GLOBALS['engine_failed'] = $failed;939
$GLOBALS['engine_passed'] = $passed;@@ -0,0 +1,205 @@
1
<?php
2
declare(strict_types=1);
3
// php server/tests/run.php
4
define('ALLIANTIES_NO_SESSION', true);
5
define('ALLIANTIES_TEST_SUITE', true);
6
require dirname(__DIR__) . '/lib/bootstrap.php';
7
require dirname(__DIR__) . '/lib/Store.php';
8
9
require __DIR__ . '/engine_test.php';
10
11
$failed = (int) ($GLOBALS['engine_failed'] ?? 0);
12
$passed = (int) ($GLOBALS['engine_passed'] ?? 0);
13
14
function expect2(bool $cond, string $msg): void
15
{
16
global $failed, $passed;
17
if ($cond) {
18
$passed++;
19
echo " ok $msg\n";
20
} else {
21
$failed++;
22
echo " FAIL $msg\n";
23
}
24
}
25
26
$tmp = sys_get_temp_dir() . '/allianties-test-' . bin2hex(random_bytes(6));
27
mkdir($tmp, 0775, true);
28
putenv('ALLIANTIES_DATA_DIR=' . $tmp);
29
// localDev() looks at HTTP_HOST — not set in CLI. debug_advance checks localDev.
30
$_SERVER['HTTP_HOST'] = '127.0.0.1';
31
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
32
33
echo "Store: lobby, join, start, actions, sync\n";
34
$store = Store::open($tmp);
35
36
$a = $store->createLobby('local:test_user_1', 'Alice', 'images/avatars/test_user_1.svg', []);
37
expect2(isset($a['id'], $a['code']), 'create lobby');
38
expect2($a['status'] === 'lobby', 'status lobby');
39
expect2(strlen($a['code']) === 6, '6-char code: ' . $a['code']);
40
expect2($a['rules']['jury'] === true, 'jury on');
41
expect2($a['rules']['shrinking_arena'] === false, 'shrink off');
42
expect2($a['rules']['ceasefire'] === false, 'ceasefire off');
43
44
try {
45
$store->startGame('local:test_user_1', $a['id']);
46
expect2(false, 'start alone');
47
} catch (RuntimeException $e) {
48
expect2($e->getMessage() === 'min_players', 'start alone refused');
49
}
50
51
$b = $store->joinByCode('local:test_user_2', 'Bob', 'images/avatars/test_user_2.svg', $a['code']);
52
expect2(count($b['players']) === 2, 'Bob joined');
53
expect2($b['id'] === $a['id'], 'same lobby');
54
55
// Case-insensitive join of already-present player (re-open).
56
$again = $store->joinByCode('local:test_user_2', 'Bob', null, strtolower($a['code']));
57
expect2(count($again['players']) === 2, 're-join is idempotent');
58
59
try {
60
$store->startGame('local:test_user_2', $a['id']);
61
expect2(false, 'non-host start');
62
} catch (RuntimeException $e) {
63
expect2($e->getMessage() === 'not_host', 'non-host refused');
64
}
65
66
$g = $store->setRules('local:test_user_1', $a['id'], [
67
'jury' => true,
68
'shrinking_arena' => true,
69
'shrink_interval_days' => 3,
70
'ceasefire' => true,
71
'ceasefire_ranges' => [['start' => '22:00', 'end' => '06:00']],
72
]);
73
expect2($g['rules']['shrinking_arena'] === true, 'host set shrink on');
74
expect2($g['rules']['shrink_interval_days'] === 3, 'interval 3');
75
expect2($g['rules']['ceasefire'] === true, 'ceasefire on');
76
expect2(count($g['rules']['ceasefire_ranges']) === 1, 'one range stored');
77
78
$g = $store->startGame('local:test_user_1', $a['id']);
79
expect2($g['status'] === 'running', 'started');
80
expect2($g['players'][0]['ap'] === 1, '1 AP at start');
81
82
$view1 = $store->view($g, 'local:test_user_1');
83
expect2($view1['status'] === 'running', 'view running');
84
expect2(isset($view1['legal']['move']), 'legal moves in view');
85
expect2($view1['version'] >= 1, 'has version');
86
expect2(isset($view1['server_now']), 'has server_now');
87
expect2($view1['timezone'] === 'Europe/Amsterdam', 'timezone');
88
89
// Sync: same version → no game payload
90
$sync = $store->sync('local:test_user_1', $a['id'], $view1['version']);
91
expect2($sync['changed'] === false, 'unchanged sync');
92
expect2(!isset($sync['game']), 'no full state when unchanged');
93
expect2(isset($sync['next_distribution_at'], $sync['server_now']), 'lightweight fields present');
94
95
// Alice moves
96
$legal = Engine::legal($g, 'local:test_user_1', $store->now());
97
expect2(!empty($legal['move']), 'Alice can move');
98
$t = $legal['move'][0];
99
$g = $store->act('local:test_user_1', $a['id'], ['type' => 'move', 'x' => $t['x'], 'y' => $t['y']]);
100
expect2($g['players'][0]['ap'] === 0, 'AP spent');
101
$view2 = $store->view($g, 'local:test_user_1');
102
$sync = $store->sync('local:test_user_2', $a['id'], $view1['version']);
103
expect2($sync['changed'] === true, 'Bob sees a change');
104
expect2(isset($sync['game']['events']), 'full state on change');
105
expect2($sync['game']['players'][0]['x'] === $t['x'], 'Bob sees Alice’s new position');
106
107
// Notes privacy through present
108
$g = $store->setNote('local:test_user_1', $a['id'], 'local:test_user_2', 'suspicious');
109
$va = $store->view($g, 'local:test_user_1');
110
$vb = $store->view($g, 'local:test_user_2');
111
$noteA = '';
112
$noteB = '';
113
foreach ($va['players'] as $p) {
114
if ($p['id'] === 'local:test_user_2') {
115
$noteA = $p['note'];
116
}
117
}
118
foreach ($vb['players'] as $p) {
119
if ($p['id'] === 'local:test_user_2') {
120
$noteB = $p['note'];
121
}
122
}
123
expect2($noteA === 'suspicious', 'Alice sees her note');
124
expect2($noteB === '', 'Bob does not');
125
126
$g = $store->addMessage('local:test_user_1', $a['id'], 'local:test_user_2', 'hi bob');
127
$va = $store->view($g, 'local:test_user_1');
128
$vb = $store->view($g, 'local:test_user_2');
129
expect2(count($va['messages']) === 1, 'Alice sees message');
130
expect2(count($vb['messages']) === 1 && $vb['messages'][0]['text'] === 'hi bob', 'Bob sees message');
131
132
// Third player cannot join after start
133
try {
134
$store->joinByCode('local:test_user_3', 'Cara', null, $a['code']);
135
expect2(false, 'join after start');
136
} catch (RuntimeException $e) {
137
expect2($e->getMessage() === 'game_started', 'join after start refused');
138
}
139
140
// Locale
141
$loc = $store->setLocale('local:test_user_1', 'nl');
142
expect2($loc === 'nl', 'locale stored');
143
expect2($store->locale('local:test_user_1') === 'nl', 'locale read');
144
$loc = $store->setLocale('local:test_user_1', 'zh-Hans');
145
expect2($loc === 'zh', 'zh-Hans normalised to zh');
146
147
// List
148
$list = $store->listFor('local:test_user_1');
149
expect2(count($list) === 1 && $list[0]['status'] === 'running', 'listed running game');
150
151
// Concurrent-ish: two IMMEDIATE transactions in sequence (same process)
152
$g = $store->createLobby('local:test_user_3', 'Cara', null, ['jury' => false]);
153
$store->joinByCode('local:test_user_4', 'Dan', null, $g['code']);
154
$g = $store->startGame('local:test_user_3', $g['id']);
155
$store->act('local:test_user_3', $g['id'], ['type' => 'surrender']);
156
$g = $store->present('local:test_user_4', $g['id']);
157
expect2($g['status'] === 'finished' && $g['winner_id'] === 'local:test_user_4', 'Dan wins after Cara surrenders');
158
159
// Unknown code
160
try {
161
$store->joinByCode('local:test_user_1', 'Alice', null, 'XXXXXX');
162
expect2(false, 'unknown code');
163
} catch (RuntimeException $e) {
164
expect2($e->getMessage() === 'unknown_code', 'unknown_code');
165
}
166
167
// Anti-race: nested mutate is fine (txDepth); invalid action rolls back AP
168
$lobby = $store->createLobby('local:test_user_5', 'Eve', null, []);
169
$store->joinByCode('local:test_user_6', 'Fay', null, $lobby['code']);
170
$g = $store->startGame('local:test_user_5', $lobby['id']);
171
$apBefore = $g['players'][0]['ap'];
172
try {
173
$store->act('local:test_user_5', $lobby['id'], ['type' => 'shoot', 'target' => 'nobody']);
174
expect2(false, 'bad shoot');
175
} catch (RuntimeException $e) {
176
expect2($e->getMessage() === 'out_of_range', 'bad shoot refused: ' . $e->getMessage());
177
}
178
$g = $store->load($lobby['id']);
179
expect2((int) $g['players'][0]['ap'] === $apBefore, 'AP unchanged after refused action (rollback)');
180
181
182
echo "safeNext\n";
183
expect2(safeNext(null) === null, 'null next');
184
expect2(safeNext('') === null, 'empty next');
185
expect2(safeNext('index.html') === 'index.html', 'plain path');
186
expect2(safeNext('index.html?join=AQBYH9') === 'index.html?join=AQBYH9', 'join query with =');
187
expect2(safeNext('index.html?join=AQBYH9&from=invite') === 'index.html?join=AQBYH9&from=invite', 'ampersand');
188
expect2(safeNext('index.html?join=ABC#frag') === 'index.html?join=ABC#frag', 'hash fragment');
189
expect2(safeNext('https://evil.example') === null, 'rejects scheme');
190
expect2(safeNext('//evil.example') === null, 'rejects protocol-relative');
191
expect2(safeNext('/etc/passwd') === null, 'rejects absolute path');
192
expect2(safeNext('index.html\\x') === null, 'rejects backslash');
193
194
echo "\nTotal passed: $passed Failed: $failed\n";
195
196
// Cleanup
197
$files = glob($tmp . '/*');
198
if (is_array($files)) {
199
foreach ($files as $f) {
200
@unlink($f);
201
}
202
}
203
@rmdir($tmp);
204
205
exit($failed > 0 ? 1 : 0);
@@ -0,0 +1,205 @@1
<?php2
declare(strict_types=1);3
// php server/tests/run.php4
define('ALLIANTIES_NO_SESSION', true);5
define('ALLIANTIES_TEST_SUITE', true);6
require dirname(__DIR__) . '/lib/bootstrap.php';7
require dirname(__DIR__) . '/lib/Store.php';8
9
require __DIR__ . '/engine_test.php';10
11
$failed = (int) ($GLOBALS['engine_failed'] ?? 0);12
$passed = (int) ($GLOBALS['engine_passed'] ?? 0);13
14
function expect2(bool $cond, string $msg): void15
{16
global $failed, $passed;17
if ($cond) {18
$passed++;19
echo " ok $msg\n";20
} else {21
$failed++;22
echo " FAIL $msg\n";23
}24
}25
26
$tmp = sys_get_temp_dir() . '/allianties-test-' . bin2hex(random_bytes(6));27
mkdir($tmp, 0775, true);28
putenv('ALLIANTIES_DATA_DIR=' . $tmp);29
// localDev() looks at HTTP_HOST — not set in CLI. debug_advance checks localDev.30
$_SERVER['HTTP_HOST'] = '127.0.0.1';31
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';32
33
echo "Store: lobby, join, start, actions, sync\n";34
$store = Store::open($tmp);35
36
$a = $store->createLobby('local:test_user_1', 'Alice', 'images/avatars/test_user_1.svg', []);37
expect2(isset($a['id'], $a['code']), 'create lobby');38
expect2($a['status'] === 'lobby', 'status lobby');39
expect2(strlen($a['code']) === 6, '6-char code: ' . $a['code']);40
expect2($a['rules']['jury'] === true, 'jury on');41
expect2($a['rules']['shrinking_arena'] === false, 'shrink off');42
expect2($a['rules']['ceasefire'] === false, 'ceasefire off');43
44
try {45
$store->startGame('local:test_user_1', $a['id']);46
expect2(false, 'start alone');47
} catch (RuntimeException $e) {48
expect2($e->getMessage() === 'min_players', 'start alone refused');49
}50
51
$b = $store->joinByCode('local:test_user_2', 'Bob', 'images/avatars/test_user_2.svg', $a['code']);52
expect2(count($b['players']) === 2, 'Bob joined');53
expect2($b['id'] === $a['id'], 'same lobby');54
55
// Case-insensitive join of already-present player (re-open).56
$again = $store->joinByCode('local:test_user_2', 'Bob', null, strtolower($a['code']));57
expect2(count($again['players']) === 2, 're-join is idempotent');58
59
try {60
$store->startGame('local:test_user_2', $a['id']);61
expect2(false, 'non-host start');62
} catch (RuntimeException $e) {63
expect2($e->getMessage() === 'not_host', 'non-host refused');64
}65
66
$g = $store->setRules('local:test_user_1', $a['id'], [67
'jury' => true,68
'shrinking_arena' => true,69
'shrink_interval_days' => 3,70
'ceasefire' => true,71
'ceasefire_ranges' => [['start' => '22:00', 'end' => '06:00']],72
]);73
expect2($g['rules']['shrinking_arena'] === true, 'host set shrink on');74
expect2($g['rules']['shrink_interval_days'] === 3, 'interval 3');75
expect2($g['rules']['ceasefire'] === true, 'ceasefire on');76
expect2(count($g['rules']['ceasefire_ranges']) === 1, 'one range stored');77
78
$g = $store->startGame('local:test_user_1', $a['id']);79
expect2($g['status'] === 'running', 'started');80
expect2($g['players'][0]['ap'] === 1, '1 AP at start');81
82
$view1 = $store->view($g, 'local:test_user_1');83
expect2($view1['status'] === 'running', 'view running');84
expect2(isset($view1['legal']['move']), 'legal moves in view');85
expect2($view1['version'] >= 1, 'has version');86
expect2(isset($view1['server_now']), 'has server_now');87
expect2($view1['timezone'] === 'Europe/Amsterdam', 'timezone');88
89
// Sync: same version → no game payload90
$sync = $store->sync('local:test_user_1', $a['id'], $view1['version']);91
expect2($sync['changed'] === false, 'unchanged sync');92
expect2(!isset($sync['game']), 'no full state when unchanged');93
expect2(isset($sync['next_distribution_at'], $sync['server_now']), 'lightweight fields present');94
95
// Alice moves96
$legal = Engine::legal($g, 'local:test_user_1', $store->now());97
expect2(!empty($legal['move']), 'Alice can move');98
$t = $legal['move'][0];99
$g = $store->act('local:test_user_1', $a['id'], ['type' => 'move', 'x' => $t['x'], 'y' => $t['y']]);100
expect2($g['players'][0]['ap'] === 0, 'AP spent');101
$view2 = $store->view($g, 'local:test_user_1');102
$sync = $store->sync('local:test_user_2', $a['id'], $view1['version']);103
expect2($sync['changed'] === true, 'Bob sees a change');104
expect2(isset($sync['game']['events']), 'full state on change');105
expect2($sync['game']['players'][0]['x'] === $t['x'], 'Bob sees Alice’s new position');106
107
// Notes privacy through present108
$g = $store->setNote('local:test_user_1', $a['id'], 'local:test_user_2', 'suspicious');109
$va = $store->view($g, 'local:test_user_1');110
$vb = $store->view($g, 'local:test_user_2');111
$noteA = '';112
$noteB = '';113
foreach ($va['players'] as $p) {114
if ($p['id'] === 'local:test_user_2') {115
$noteA = $p['note'];116
}117
}118
foreach ($vb['players'] as $p) {119
if ($p['id'] === 'local:test_user_2') {120
$noteB = $p['note'];121
}122
}123
expect2($noteA === 'suspicious', 'Alice sees her note');124
expect2($noteB === '', 'Bob does not');125
126
$g = $store->addMessage('local:test_user_1', $a['id'], 'local:test_user_2', 'hi bob');127
$va = $store->view($g, 'local:test_user_1');128
$vb = $store->view($g, 'local:test_user_2');129
expect2(count($va['messages']) === 1, 'Alice sees message');130
expect2(count($vb['messages']) === 1 && $vb['messages'][0]['text'] === 'hi bob', 'Bob sees message');131
132
// Third player cannot join after start133
try {134
$store->joinByCode('local:test_user_3', 'Cara', null, $a['code']);135
expect2(false, 'join after start');136
} catch (RuntimeException $e) {137
expect2($e->getMessage() === 'game_started', 'join after start refused');138
}139
140
// Locale141
$loc = $store->setLocale('local:test_user_1', 'nl');142
expect2($loc === 'nl', 'locale stored');143
expect2($store->locale('local:test_user_1') === 'nl', 'locale read');144
$loc = $store->setLocale('local:test_user_1', 'zh-Hans');145
expect2($loc === 'zh', 'zh-Hans normalised to zh');146
147
// List148
$list = $store->listFor('local:test_user_1');149
expect2(count($list) === 1 && $list[0]['status'] === 'running', 'listed running game');150
151
// Concurrent-ish: two IMMEDIATE transactions in sequence (same process)152
$g = $store->createLobby('local:test_user_3', 'Cara', null, ['jury' => false]);153
$store->joinByCode('local:test_user_4', 'Dan', null, $g['code']);154
$g = $store->startGame('local:test_user_3', $g['id']);155
$store->act('local:test_user_3', $g['id'], ['type' => 'surrender']);156
$g = $store->present('local:test_user_4', $g['id']);157
expect2($g['status'] === 'finished' && $g['winner_id'] === 'local:test_user_4', 'Dan wins after Cara surrenders');158
159
// Unknown code160
try {161
$store->joinByCode('local:test_user_1', 'Alice', null, 'XXXXXX');162
expect2(false, 'unknown code');163
} catch (RuntimeException $e) {164
expect2($e->getMessage() === 'unknown_code', 'unknown_code');165
}166
167
// Anti-race: nested mutate is fine (txDepth); invalid action rolls back AP168
$lobby = $store->createLobby('local:test_user_5', 'Eve', null, []);169
$store->joinByCode('local:test_user_6', 'Fay', null, $lobby['code']);170
$g = $store->startGame('local:test_user_5', $lobby['id']);171
$apBefore = $g['players'][0]['ap'];172
try {173
$store->act('local:test_user_5', $lobby['id'], ['type' => 'shoot', 'target' => 'nobody']);174
expect2(false, 'bad shoot');175
} catch (RuntimeException $e) {176
expect2($e->getMessage() === 'out_of_range', 'bad shoot refused: ' . $e->getMessage());177
}178
$g = $store->load($lobby['id']);179
expect2((int) $g['players'][0]['ap'] === $apBefore, 'AP unchanged after refused action (rollback)');180
181
182
echo "safeNext\n";183
expect2(safeNext(null) === null, 'null next');184
expect2(safeNext('') === null, 'empty next');185
expect2(safeNext('index.html') === 'index.html', 'plain path');186
expect2(safeNext('index.html?join=AQBYH9') === 'index.html?join=AQBYH9', 'join query with =');187
expect2(safeNext('index.html?join=AQBYH9&from=invite') === 'index.html?join=AQBYH9&from=invite', 'ampersand');188
expect2(safeNext('index.html?join=ABC#frag') === 'index.html?join=ABC#frag', 'hash fragment');189
expect2(safeNext('https://evil.example') === null, 'rejects scheme');190
expect2(safeNext('//evil.example') === null, 'rejects protocol-relative');191
expect2(safeNext('/etc/passwd') === null, 'rejects absolute path');192
expect2(safeNext('index.html\\x') === null, 'rejects backslash');193
194
echo "\nTotal passed: $passed Failed: $failed\n";195
196
// Cleanup197
$files = glob($tmp . '/*');198
if (is_array($files)) {199
foreach ($files as $f) {200
@unlink($f);201
}202
}203
@rmdir($tmp);204
205
exit($failed > 0 ? 1 : 0);@@ -0,0 +1,172 @@
1
'use strict';
2
3
var Api = {
4
csrf: null,
5
me: null,
6
configured: false,
7
local: false,
8
defaults: null,
9
timezone: 'Europe/Amsterdam',
10
serverNow: null,
11
syncedAtMs: null
12
};
13
14
Api._url = function (action, query)
15
{
16
var u = 'api.php?action=' + encodeURIComponent(action);
17
if (query)
18
{
19
Object.keys(query).forEach(function (k)
20
{
21
if (query[k] != null)
22
{ u += '&' + encodeURIComponent(k) + '=' + encodeURIComponent(query[k]); }
23
});
24
}
25
return u;
26
};
27
28
Api.call = function (action, body, method)
29
{
30
method = method || (body ? 'POST' : 'GET');
31
var opts = {
32
method: method,
33
credentials: 'same-origin',
34
headers: { Accept: 'application/json' }
35
};
36
if (method !== 'GET')
37
{
38
opts.headers['Content-Type'] = 'application/json';
39
if (this.csrf)
40
{ opts.headers['X-CSRF-TOKEN'] = this.csrf; }
41
var payload = Object.assign({ action: action }, body || {});
42
opts.body = JSON.stringify(payload);
43
}
44
var url = method === 'GET' ? this._url(action, body) : this._url(action);
45
return fetch(url, opts).then(function (res)
46
{
47
return res.json().then(function (data)
48
{
49
if (!data || typeof data !== 'object')
50
{ throw new Error('generic'); }
51
if (data.csrf)
52
{ Api.csrf = data.csrf; }
53
if (typeof data.server_now === 'number')
54
{
55
Api.serverNow = data.server_now;
56
Api.syncedAtMs = Date.now();
57
}
58
if (!data.ok && data.error)
59
{
60
var err = new Error(data.error);
61
err.code = data.error;
62
err.http = res.status;
63
throw err;
64
}
65
if (!res.ok)
66
{
67
var e2 = new Error('serverStatus');
68
e2.code = 'serverStatus';
69
e2.status = res.status;
70
throw e2;
71
}
72
return data;
73
}, function ()
74
{
75
var e = new Error('serverStatus');
76
e.status = res.status;
77
throw e;
78
});
79
});
80
};
81
82
Api.now = function ()
83
{
84
if (this.serverNow == null || this.syncedAtMs == null)
85
{ return Math.floor(Date.now() / 1000); }
86
return this.serverNow + (Date.now() - this.syncedAtMs) / 1000;
87
};
88
89
Api.loadMe = function ()
90
{
91
var self = this;
92
return this.call('me').then(function (data)
93
{
94
self.me = data.me || null;
95
self.configured = !!data.configured;
96
self.local = !!data.local;
97
self.defaults = data.defaults || Rules.defaultRules();
98
self.timezone = data.timezone || 'Europe/Amsterdam';
99
return data;
100
});
101
};
102
103
Api.setLocale = function (id)
104
{
105
if (!this.me) { return Promise.resolve(); }
106
return this.call('set_locale', { locale: id });
107
};
108
109
Api.createLobby = function (rules)
110
{
111
return this.call('lobby_create', { rules: rules });
112
};
113
114
Api.join = function (code)
115
{
116
return this.call('lobby_join', { code: code });
117
};
118
119
Api.leave = function (gameId)
120
{
121
return this.call('lobby_leave', { game: gameId });
122
};
123
124
Api.setRules = function (gameId, rules)
125
{
126
return this.call('lobby_rules', { game: gameId, rules: rules });
127
};
128
129
Api.start = function (gameId)
130
{
131
return this.call('lobby_start', { game: gameId });
132
};
133
134
Api.act = function (gameId, action)
135
{
136
return this.call('act', Object.assign({ game: gameId }, action));
137
};
138
139
Api.note = function (gameId, subject, text)
140
{
141
return this.call('note', { game: gameId, subject: subject, text: text });
142
};
143
144
Api.message = function (gameId, to, text)
145
{
146
return this.call('message', { game: gameId, to: to, text: text });
147
};
148
149
Api.sync = function (gameId, version)
150
{
151
return this.call('sync', { game: gameId, v: version }, 'GET');
152
};
153
154
Api.game = function (gameId)
155
{
156
return this.call('game', { game: gameId }, 'GET');
157
};
158
159
Api.games = function ()
160
{
161
return this.call('games');
162
};
163
164
Api.debugAdvance = function (gameId, days)
165
{
166
return this.call('debug_advance', { game: gameId, days: days || 1 });
167
};
168
169
if (typeof module !== 'undefined' && module.exports)
170
{ module.exports = Api; }
171
else if (typeof globalThis !== 'undefined')
172
{ globalThis.Api = Api; }
@@ -0,0 +1,172 @@1
'use strict';2
3
var Api = {4
csrf: null,5
me: null,6
configured: false,7
local: false,8
defaults: null,9
timezone: 'Europe/Amsterdam',10
serverNow: null,11
syncedAtMs: null12
};13
14
Api._url = function (action, query)15
{16
var u = 'api.php?action=' + encodeURIComponent(action);17
if (query)18
{19
Object.keys(query).forEach(function (k)20
{21
if (query[k] != null)22
{ u += '&' + encodeURIComponent(k) + '=' + encodeURIComponent(query[k]); }23
});24
}25
return u;26
};27
28
Api.call = function (action, body, method)29
{30
method = method || (body ? 'POST' : 'GET');31
var opts = {32
method: method,33
credentials: 'same-origin',34
headers: { Accept: 'application/json' }35
};36
if (method !== 'GET')37
{38
opts.headers['Content-Type'] = 'application/json';39
if (this.csrf)40
{ opts.headers['X-CSRF-TOKEN'] = this.csrf; }41
var payload = Object.assign({ action: action }, body || {});42
opts.body = JSON.stringify(payload);43
}44
var url = method === 'GET' ? this._url(action, body) : this._url(action);45
return fetch(url, opts).then(function (res)46
{47
return res.json().then(function (data)48
{49
if (!data || typeof data !== 'object')50
{ throw new Error('generic'); }51
if (data.csrf)52
{ Api.csrf = data.csrf; }53
if (typeof data.server_now === 'number')54
{55
Api.serverNow = data.server_now;56
Api.syncedAtMs = Date.now();57
}58
if (!data.ok && data.error)59
{60
var err = new Error(data.error);61
err.code = data.error;62
err.http = res.status;63
throw err;64
}65
if (!res.ok)66
{67
var e2 = new Error('serverStatus');68
e2.code = 'serverStatus';69
e2.status = res.status;70
throw e2;71
}72
return data;73
}, function ()74
{75
var e = new Error('serverStatus');76
e.status = res.status;77
throw e;78
});79
});80
};81
82
Api.now = function ()83
{84
if (this.serverNow == null || this.syncedAtMs == null)85
{ return Math.floor(Date.now() / 1000); }86
return this.serverNow + (Date.now() - this.syncedAtMs) / 1000;87
};88
89
Api.loadMe = function ()90
{91
var self = this;92
return this.call('me').then(function (data)93
{94
self.me = data.me || null;95
self.configured = !!data.configured;96
self.local = !!data.local;97
self.defaults = data.defaults || Rules.defaultRules();98
self.timezone = data.timezone || 'Europe/Amsterdam';99
return data;100
});101
};102
103
Api.setLocale = function (id)104
{105
if (!this.me) { return Promise.resolve(); }106
return this.call('set_locale', { locale: id });107
};108
109
Api.createLobby = function (rules)110
{111
return this.call('lobby_create', { rules: rules });112
};113
114
Api.join = function (code)115
{116
return this.call('lobby_join', { code: code });117
};118
119
Api.leave = function (gameId)120
{121
return this.call('lobby_leave', { game: gameId });122
};123
124
Api.setRules = function (gameId, rules)125
{126
return this.call('lobby_rules', { game: gameId, rules: rules });127
};128
129
Api.start = function (gameId)130
{131
return this.call('lobby_start', { game: gameId });132
};133
134
Api.act = function (gameId, action)135
{136
return this.call('act', Object.assign({ game: gameId }, action));137
};138
139
Api.note = function (gameId, subject, text)140
{141
return this.call('note', { game: gameId, subject: subject, text: text });142
};143
144
Api.message = function (gameId, to, text)145
{146
return this.call('message', { game: gameId, to: to, text: text });147
};148
149
Api.sync = function (gameId, version)150
{151
return this.call('sync', { game: gameId, v: version }, 'GET');152
};153
154
Api.game = function (gameId)155
{156
return this.call('game', { game: gameId }, 'GET');157
};158
159
Api.games = function ()160
{161
return this.call('games');162
};163
164
Api.debugAdvance = function (gameId, days)165
{166
return this.call('debug_advance', { game: gameId, days: days || 1 });167
};168
169
if (typeof module !== 'undefined' && module.exports)170
{ module.exports = Api; }171
else if (typeof globalThis !== 'undefined')172
{ globalThis.Api = Api; }@@ -0,0 +1,58 @@
1
#!/usr/bin/env bash
2
# Concatenate sources into build/game.js and copy the PHP API into build/.
3
# data/config.php and any sqlite are NEVER copied.
4
set -euo pipefail
5
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
6
BUILD_FILE="$ROOT/build/game.js"
7
SRC_DIR="$ROOT/src"
8
9
mkdir -p "$ROOT/build"
10
11
printf "Build started, output file: %s\n" "$BUILD_FILE"
12
rm -f "$BUILD_FILE"
13
14
FILES=(
15
"$SRC_DIR/i18n.js"
16
"$SRC_DIR/rules.js"
17
"$SRC_DIR/api.js"
18
"$SRC_DIR/main.js"
19
)
20
21
{
22
printf '%s\n' "/*"
23
printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND."
24
printf '%s\n' " * Built by src/build.sh from the sources in src/."
25
printf '%s\n' " */"
26
printf '%s' "var I18N_CATALOG = "
27
cat "$ROOT/server/lib/i18n.json"
28
printf ';\n'
29
} >> "$BUILD_FILE"
30
31
for file in "${FILES[@]}"
32
do
33
if [[ ! -f "$file" ]]
34
then
35
printf "Missing source file: %s\n" "$file" >&2
36
exit 1
37
fi
38
printf "\n/*\n * Start File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
39
printf "Building %s\n" "$file"
40
cat "$file" >> "$BUILD_FILE"
41
printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
42
done
43
44
SERVER="$ROOT/server"
45
cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
46
"$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
47
"$ROOT/build/"
48
mkdir -p "$ROOT/build/lib"
49
cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
50
"$SERVER/lib/Engine.php" "$SERVER/lib/i18n.json" "$SERVER/lib/I18n.php" \
51
"$ROOT/build/lib/"
52
mkdir -p "$ROOT/build/data"
53
cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
54
rm -f "$ROOT/build/data/config.php" "$ROOT/build/data/config.lock"
55
rm -f "$ROOT/build/data/"*.sqlite "$ROOT/build/data/"*.sqlite-journal
56
rm -rf "$ROOT/build/data/sessions"
57
58
printf "DONE\n"
@@ -0,0 +1,58 @@1
#!/usr/bin/env bash2
# Concatenate sources into build/game.js and copy the PHP API into build/.3
# data/config.php and any sqlite are NEVER copied.4
set -euo pipefail5
ROOT="$(cd "$(dirname "$0")/.." && pwd)"6
BUILD_FILE="$ROOT/build/game.js"7
SRC_DIR="$ROOT/src"8
9
mkdir -p "$ROOT/build"10
11
printf "Build started, output file: %s\n" "$BUILD_FILE"12
rm -f "$BUILD_FILE"13
14
FILES=(15
"$SRC_DIR/i18n.js"16
"$SRC_DIR/rules.js"17
"$SRC_DIR/api.js"18
"$SRC_DIR/main.js"19
)20
21
{22
printf '%s\n' "/*"23
printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND."24
printf '%s\n' " * Built by src/build.sh from the sources in src/."25
printf '%s\n' " */"26
printf '%s' "var I18N_CATALOG = "27
cat "$ROOT/server/lib/i18n.json"28
printf ';\n'29
} >> "$BUILD_FILE"30
31
for file in "${FILES[@]}"32
do33
if [[ ! -f "$file" ]]34
then35
printf "Missing source file: %s\n" "$file" >&236
exit 137
fi38
printf "\n/*\n * Start File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"39
printf "Building %s\n" "$file"40
cat "$file" >> "$BUILD_FILE"41
printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"42
done43
44
SERVER="$ROOT/server"45
cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \46
"$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \47
"$ROOT/build/"48
mkdir -p "$ROOT/build/lib"49
cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \50
"$SERVER/lib/Engine.php" "$SERVER/lib/i18n.json" "$SERVER/lib/I18n.php" \51
"$ROOT/build/lib/"52
mkdir -p "$ROOT/build/data"53
cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"54
rm -f "$ROOT/build/data/config.php" "$ROOT/build/data/config.lock"55
rm -f "$ROOT/build/data/"*.sqlite "$ROOT/build/data/"*.sqlite-journal56
rm -rf "$ROOT/build/data/sessions"57
58
printf "DONE\n"@@ -0,0 +1,383 @@
1
'use strict';
2
3
/**
4
* Player-facing translations for Allianties.
5
* Default locale is English. The player's choice is stored in
6
* localStorage and, when they are logged in, on their server profile.
7
*/
8
9
var I18n = {
10
LOCALES: [
11
{ id: 'en', flag: 'gb', endonym: 'English', htmlLang: 'en' },
12
{ id: 'nl', flag: 'nl', endonym: 'Nederlands', htmlLang: 'nl' },
13
{ id: 'de', flag: 'de', endonym: 'Deutsch', htmlLang: 'de' },
14
{ id: 'fr', flag: 'fr', endonym: 'Français', htmlLang: 'fr' },
15
{ id: 'ja', flag: 'jp', endonym: '日本語', htmlLang: 'ja' },
16
{ id: 'zh', flag: 'cn', endonym: '简体中文', htmlLang: 'zh-Hans' },
17
{ id: 'ko', flag: 'kr', endonym: '한국어', htmlLang: 'ko' },
18
{ id: 'pl', flag: 'pl', endonym: 'Polski', htmlLang: 'pl' },
19
{ id: 'ru', flag: 'ru', endonym: 'Русский', htmlLang: 'ru' },
20
{ id: 'es', flag: 'es', endonym: 'Español', htmlLang: 'es' }
21
],
22
DEFAULT: 'en',
23
STORAGE_KEY: 'allianties-locale',
24
COOKIE: 'allianties-locale',
25
locale: 'en',
26
_catalog: null,
27
_listeners: [],
28
_pickerOpen: false
29
};
30
31
I18n._load = function ()
32
{
33
if (this._catalog)
34
{ return this._catalog; }
35
var data = null;
36
if (typeof I18N_CATALOG !== 'undefined' && I18N_CATALOG)
37
{ data = I18N_CATALOG; }
38
else if (typeof require !== 'undefined')
39
{
40
try
41
{ data = require('../server/lib/i18n.json'); }
42
catch (e) { data = null; }
43
}
44
this._catalog = data && data.locales ? data : { locales: { en: {} }, errors: {} };
45
return this._catalog;
46
};
47
48
I18n.known = function (id)
49
{
50
if (!id)
51
{ return false; }
52
for (var i = 0; i < this.LOCALES.length; i++)
53
{
54
if (this.LOCALES[i].id === id)
55
{ return true; }
56
}
57
return false;
58
};
59
60
I18n.info = function (id)
61
{
62
id = id || this.locale;
63
for (var i = 0; i < this.LOCALES.length; i++)
64
{
65
if (this.LOCALES[i].id === id)
66
{ return this.LOCALES[i]; }
67
}
68
return this.LOCALES[0];
69
};
70
71
I18n.t = function (key, params, fallback)
72
{
73
this._load();
74
var loc = this._catalog.locales[this.locale] || {};
75
var en = this._catalog.locales.en || {};
76
var s = loc[key];
77
if (s == null || s === '')
78
{ s = en[key]; }
79
if (s == null || s === '')
80
{ s = fallback != null ? fallback : key; }
81
s = String(s);
82
if (params)
83
{
84
s = s.replace(/\{(\w+)\}/g, function (_, k)
85
{
86
return params[k] != null ? String(params[k]) : '';
87
});
88
}
89
return s;
90
};
91
92
/** Slavic-style plural: one / few / many (falls back to other). */
93
I18n.pluralForm = function (n, locale)
94
{
95
n = Math.abs(parseInt(n, 10) || 0);
96
locale = locale || this.locale;
97
if (locale === 'ru')
98
{
99
var mod10 = n % 10, mod100 = n % 100;
100
if (mod10 === 1 && mod100 !== 11)
101
{ return 'one'; }
102
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14))
103
{ return 'few'; }
104
return 'many';
105
}
106
if (locale === 'pl')
107
{
108
if (n === 1)
109
{ return 'one'; }
110
var mod10 = n % 10, mod100 = n % 100;
111
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14))
112
{ return 'few'; }
113
return 'many';
114
}
115
if (locale === 'fr' || locale === 'es')
116
{ return (n === 0 || n === 1) ? 'one' : 'other'; }
117
if (locale === 'ja' || locale === 'zh' || locale === 'ko')
118
{ return 'other'; }
119
return n === 1 ? 'one' : 'other';
120
};
121
122
I18n.plural = function (base, n, params)
123
{
124
params = params || {};
125
params.n = n;
126
var form = this.pluralForm(n);
127
var key = base + '.' + form;
128
this._load();
129
var loc = this._catalog.locales[this.locale] || {};
130
var en = this._catalog.locales.en || {};
131
if (loc[key] == null && en[key] == null)
132
{
133
if (form === 'few' || form === 'many')
134
{ key = base + '.other'; }
135
}
136
if ((loc[key] == null && en[key] == null) && form !== 'one')
137
{ key = base + '.other'; }
138
return this.t(key, params);
139
};
140
141
I18n.error = function (msg)
142
{
143
if (!msg)
144
{ return ''; }
145
this._load();
146
var map = this._catalog.errors || {};
147
if (map[msg])
148
{ return this.t(map[msg]); }
149
var m = /^The server returned (\d+)\.$/.exec(msg) || /^De server gaf (\d+)$/.exec(msg);
150
if (m)
151
{ return this.t('error.serverStatus', { status: m[1] }); }
152
return msg;
153
};
154
155
I18n.readStored = function ()
156
{
157
try
158
{
159
if (typeof localStorage !== 'undefined')
160
{
161
var v = localStorage.getItem(this.STORAGE_KEY);
162
if (this.known(v))
163
{ return v; }
164
}
165
}
166
catch (e) { /* private mode */ }
167
return this.DEFAULT;
168
};
169
170
I18n._writeStored = function (id)
171
{
172
try
173
{
174
if (typeof localStorage !== 'undefined')
175
{ localStorage.setItem(this.STORAGE_KEY, id); }
176
}
177
catch (e) { /* ignore */ }
178
try
179
{
180
if (typeof document !== 'undefined')
181
{
182
document.cookie = this.COOKIE + '=' + encodeURIComponent(id)
183
+ ';path=/;max-age=31536000;SameSite=Lax';
184
}
185
}
186
catch (e) { /* ignore */ }
187
};
188
189
I18n.setLocale = function (id, opts)
190
{
191
opts = opts || {};
192
if (!this.known(id))
193
{ id = this.DEFAULT; }
194
var changed = id !== this.locale;
195
this.locale = id;
196
if (opts.persist !== false)
197
{ this._writeStored(id); }
198
if (typeof document !== 'undefined' && document.documentElement)
199
{
200
document.documentElement.lang = this.info(id).htmlLang;
201
document.documentElement.setAttribute('data-locale', id);
202
}
203
this.apply();
204
this.renderPicker();
205
if (changed || opts.force)
206
{
207
for (var i = 0; i < this._listeners.length; i++)
208
{
209
try
210
{ this._listeners[i](id); }
211
catch (e) { /* listener errors must not break i18n */ }
212
}
213
}
214
if (opts.sync !== false && typeof Api !== 'undefined' && Api.me && Api.setLocale)
215
{ Api.setLocale(id); }
216
return id;
217
};
218
219
I18n.onChange = function (fn)
220
{
221
if (typeof fn === 'function')
222
{ this._listeners.push(fn); }
223
};
224
225
I18n.apply = function (root)
226
{
227
if (typeof document === 'undefined')
228
{ return; }
229
root = root || document;
230
var nodes = root.querySelectorAll('[data-i18n]');
231
for (var i = 0; i < nodes.length; i++)
232
{
233
var el = nodes[i];
234
var key = el.getAttribute('data-i18n');
235
if (!key)
236
{ continue; }
237
el.textContent = this.t(key);
238
}
239
nodes = root.querySelectorAll('[data-i18n-html]');
240
for (var i = 0; i < nodes.length; i++)
241
{
242
var el = nodes[i];
243
var key = el.getAttribute('data-i18n-html');
244
if (!key)
245
{ continue; }
246
el.innerHTML = this.t(key);
247
}
248
nodes = root.querySelectorAll('[data-i18n-placeholder]');
249
for (var i = 0; i < nodes.length; i++)
250
{
251
nodes[i].setAttribute('placeholder', this.t(nodes[i].getAttribute('data-i18n-placeholder')));
252
}
253
nodes = root.querySelectorAll('[data-i18n-aria]');
254
for (var i = 0; i < nodes.length; i++)
255
{
256
nodes[i].setAttribute('aria-label', this.t(nodes[i].getAttribute('data-i18n-aria')));
257
}
258
nodes = root.querySelectorAll('[data-i18n-title]');
259
for (var i = 0; i < nodes.length; i++)
260
{
261
nodes[i].setAttribute('title', this.t(nodes[i].getAttribute('data-i18n-title')));
262
}
263
};
264
265
I18n.flagUrl = function (id)
266
{
267
var info = this.info(id);
268
return 'images/flags/' + info.flag + '.svg';
269
};
270
271
I18n.togglePicker = function (force)
272
{
273
if (typeof force === 'boolean')
274
{ this._pickerOpen = force; }
275
else
276
{ this._pickerOpen = !this._pickerOpen; }
277
this.renderPicker();
278
};
279
280
I18n.renderPicker = function ()
281
{
282
if (typeof document === 'undefined')
283
{ return; }
284
var wrap = document.getElementById('lang-picker');
285
var btn = document.getElementById('lang-current');
286
var list = document.getElementById('lang-list');
287
if (!wrap || !btn || !list)
288
{ return; }
289
var info = this.info();
290
var img = btn.querySelector('img');
291
if (img)
292
{
293
img.src = this.flagUrl(this.locale);
294
img.alt = info.endonym;
295
}
296
btn.setAttribute('aria-label', this.t('lang.current', { name: info.endonym }));
297
btn.setAttribute('aria-expanded', this._pickerOpen ? 'true' : 'false');
298
btn.title = info.endonym;
299
list.innerHTML = '';
300
if (!this._pickerOpen)
301
{
302
list.hidden = true;
303
wrap.classList.remove('open');
304
return;
305
}
306
wrap.classList.add('open');
307
list.hidden = false;
308
for (var i = 0; i < this.LOCALES.length; i++)
309
{
310
var loc = this.LOCALES[i];
311
var opt = document.createElement('button');
312
opt.type = 'button';
313
opt.className = 'lang-option' + (loc.id === this.locale ? ' current' : '');
314
opt.setAttribute('data-locale', loc.id);
315
opt.setAttribute('aria-label', loc.endonym);
316
opt.title = loc.endonym;
317
opt.innerHTML = '<img src="' + this.flagUrl(loc.id) + '" alt="" width="36" height="24">'
318
+ '<span>' + loc.endonym + '</span>';
319
(function (id)
320
{
321
opt.addEventListener('click', function (e)
322
{
323
e.stopPropagation();
324
I18n.setLocale(id);
325
I18n.togglePicker(false);
326
});
327
})(loc.id);
328
list.appendChild(opt);
329
}
330
};
331
332
I18n.bindPicker = function ()
333
{
334
if (typeof document === 'undefined')
335
{ return; }
336
var btn = document.getElementById('lang-current');
337
var list = document.getElementById('lang-list');
338
if (btn)
339
{
340
btn.addEventListener('click', function (e)
341
{
342
e.stopPropagation();
343
I18n.togglePicker();
344
});
345
}
346
document.addEventListener('click', function (e)
347
{
348
var wrap = document.getElementById('lang-picker');
349
if (!wrap || !I18n._pickerOpen)
350
{ return; }
351
if (!wrap.contains(e.target))
352
{ I18n.togglePicker(false); }
353
});
354
document.addEventListener('keydown', function (e)
355
{
356
if (e.key === 'Escape' && I18n._pickerOpen)
357
{ I18n.togglePicker(false); }
358
});
359
this.renderPicker();
360
};
361
362
I18n.init = function ()
363
{
364
this._load();
365
this.locale = this.readStored();
366
if (typeof document !== 'undefined' && document.documentElement)
367
{
368
document.documentElement.lang = this.info().htmlLang;
369
document.documentElement.setAttribute('data-locale', this.locale);
370
}
371
this.apply();
372
};
373
374
I18n.applyFromProfile = function (locale)
375
{
376
if (this.known(locale))
377
{ this.setLocale(locale, { sync: false, persist: true }); }
378
};
379
380
if (typeof module !== 'undefined' && module.exports)
381
{ module.exports = I18n; }
382
else if (typeof globalThis !== 'undefined')
383
{ globalThis.I18n = I18n; }
@@ -0,0 +1,383 @@1
'use strict';2
3
/**4
* Player-facing translations for Allianties.5
* Default locale is English. The player's choice is stored in6
* localStorage and, when they are logged in, on their server profile.7
*/8
9
var I18n = {10
LOCALES: [11
{ id: 'en', flag: 'gb', endonym: 'English', htmlLang: 'en' },12
{ id: 'nl', flag: 'nl', endonym: 'Nederlands', htmlLang: 'nl' },13
{ id: 'de', flag: 'de', endonym: 'Deutsch', htmlLang: 'de' },14
{ id: 'fr', flag: 'fr', endonym: 'Français', htmlLang: 'fr' },15
{ id: 'ja', flag: 'jp', endonym: '日本語', htmlLang: 'ja' },16
{ id: 'zh', flag: 'cn', endonym: '简体中文', htmlLang: 'zh-Hans' },17
{ id: 'ko', flag: 'kr', endonym: '한국어', htmlLang: 'ko' },18
{ id: 'pl', flag: 'pl', endonym: 'Polski', htmlLang: 'pl' },19
{ id: 'ru', flag: 'ru', endonym: 'Русский', htmlLang: 'ru' },20
{ id: 'es', flag: 'es', endonym: 'Español', htmlLang: 'es' }21
],22
DEFAULT: 'en',23
STORAGE_KEY: 'allianties-locale',24
COOKIE: 'allianties-locale',25
locale: 'en',26
_catalog: null,27
_listeners: [],28
_pickerOpen: false29
};30
31
I18n._load = function ()32
{33
if (this._catalog)34
{ return this._catalog; }35
var data = null;36
if (typeof I18N_CATALOG !== 'undefined' && I18N_CATALOG)37
{ data = I18N_CATALOG; }38
else if (typeof require !== 'undefined')39
{40
try41
{ data = require('../server/lib/i18n.json'); }42
catch (e) { data = null; }43
}44
this._catalog = data && data.locales ? data : { locales: { en: {} }, errors: {} };45
return this._catalog;46
};47
48
I18n.known = function (id)49
{50
if (!id)51
{ return false; }52
for (var i = 0; i < this.LOCALES.length; i++)53
{54
if (this.LOCALES[i].id === id)55
{ return true; }56
}57
return false;58
};59
60
I18n.info = function (id)61
{62
id = id || this.locale;63
for (var i = 0; i < this.LOCALES.length; i++)64
{65
if (this.LOCALES[i].id === id)66
{ return this.LOCALES[i]; }67
}68
return this.LOCALES[0];69
};70
71
I18n.t = function (key, params, fallback)72
{73
this._load();74
var loc = this._catalog.locales[this.locale] || {};75
var en = this._catalog.locales.en || {};76
var s = loc[key];77
if (s == null || s === '')78
{ s = en[key]; }79
if (s == null || s === '')80
{ s = fallback != null ? fallback : key; }81
s = String(s);82
if (params)83
{84
s = s.replace(/\{(\w+)\}/g, function (_, k)85
{86
return params[k] != null ? String(params[k]) : '';87
});88
}89
return s;90
};91
92
/** Slavic-style plural: one / few / many (falls back to other). */93
I18n.pluralForm = function (n, locale)94
{95
n = Math.abs(parseInt(n, 10) || 0);96
locale = locale || this.locale;97
if (locale === 'ru')98
{99
var mod10 = n % 10, mod100 = n % 100;100
if (mod10 === 1 && mod100 !== 11)101
{ return 'one'; }102
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14))103
{ return 'few'; }104
return 'many';105
}106
if (locale === 'pl')107
{108
if (n === 1)109
{ return 'one'; }110
var mod10 = n % 10, mod100 = n % 100;111
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14))112
{ return 'few'; }113
return 'many';114
}115
if (locale === 'fr' || locale === 'es')116
{ return (n === 0 || n === 1) ? 'one' : 'other'; }117
if (locale === 'ja' || locale === 'zh' || locale === 'ko')118
{ return 'other'; }119
return n === 1 ? 'one' : 'other';120
};121
122
I18n.plural = function (base, n, params)123
{124
params = params || {};125
params.n = n;126
var form = this.pluralForm(n);127
var key = base + '.' + form;128
this._load();129
var loc = this._catalog.locales[this.locale] || {};130
var en = this._catalog.locales.en || {};131
if (loc[key] == null && en[key] == null)132
{133
if (form === 'few' || form === 'many')134
{ key = base + '.other'; }135
}136
if ((loc[key] == null && en[key] == null) && form !== 'one')137
{ key = base + '.other'; }138
return this.t(key, params);139
};140
141
I18n.error = function (msg)142
{143
if (!msg)144
{ return ''; }145
this._load();146
var map = this._catalog.errors || {};147
if (map[msg])148
{ return this.t(map[msg]); }149
var m = /^The server returned (\d+)\.$/.exec(msg) || /^De server gaf (\d+)$/.exec(msg);150
if (m)151
{ return this.t('error.serverStatus', { status: m[1] }); }152
return msg;153
};154
155
I18n.readStored = function ()156
{157
try158
{159
if (typeof localStorage !== 'undefined')160
{161
var v = localStorage.getItem(this.STORAGE_KEY);162
if (this.known(v))163
{ return v; }164
}165
}166
catch (e) { /* private mode */ }167
return this.DEFAULT;168
};169
170
I18n._writeStored = function (id)171
{172
try173
{174
if (typeof localStorage !== 'undefined')175
{ localStorage.setItem(this.STORAGE_KEY, id); }176
}177
catch (e) { /* ignore */ }178
try179
{180
if (typeof document !== 'undefined')181
{182
document.cookie = this.COOKIE + '=' + encodeURIComponent(id)183
+ ';path=/;max-age=31536000;SameSite=Lax';184
}185
}186
catch (e) { /* ignore */ }187
};188
189
I18n.setLocale = function (id, opts)190
{191
opts = opts || {};192
if (!this.known(id))193
{ id = this.DEFAULT; }194
var changed = id !== this.locale;195
this.locale = id;196
if (opts.persist !== false)197
{ this._writeStored(id); }198
if (typeof document !== 'undefined' && document.documentElement)199
{200
document.documentElement.lang = this.info(id).htmlLang;201
document.documentElement.setAttribute('data-locale', id);202
}203
this.apply();204
this.renderPicker();205
if (changed || opts.force)206
{207
for (var i = 0; i < this._listeners.length; i++)208
{209
try210
{ this._listeners[i](id); }211
catch (e) { /* listener errors must not break i18n */ }212
}213
}214
if (opts.sync !== false && typeof Api !== 'undefined' && Api.me && Api.setLocale)215
{ Api.setLocale(id); }216
return id;217
};218
219
I18n.onChange = function (fn)220
{221
if (typeof fn === 'function')222
{ this._listeners.push(fn); }223
};224
225
I18n.apply = function (root)226
{227
if (typeof document === 'undefined')228
{ return; }229
root = root || document;230
var nodes = root.querySelectorAll('[data-i18n]');231
for (var i = 0; i < nodes.length; i++)232
{233
var el = nodes[i];234
var key = el.getAttribute('data-i18n');235
if (!key)236
{ continue; }237
el.textContent = this.t(key);238
}239
nodes = root.querySelectorAll('[data-i18n-html]');240
for (var i = 0; i < nodes.length; i++)241
{242
var el = nodes[i];243
var key = el.getAttribute('data-i18n-html');244
if (!key)245
{ continue; }246
el.innerHTML = this.t(key);247
}248
nodes = root.querySelectorAll('[data-i18n-placeholder]');249
for (var i = 0; i < nodes.length; i++)250
{251
nodes[i].setAttribute('placeholder', this.t(nodes[i].getAttribute('data-i18n-placeholder')));252
}253
nodes = root.querySelectorAll('[data-i18n-aria]');254
for (var i = 0; i < nodes.length; i++)255
{256
nodes[i].setAttribute('aria-label', this.t(nodes[i].getAttribute('data-i18n-aria')));257
}258
nodes = root.querySelectorAll('[data-i18n-title]');259
for (var i = 0; i < nodes.length; i++)260
{261
nodes[i].setAttribute('title', this.t(nodes[i].getAttribute('data-i18n-title')));262
}263
};264
265
I18n.flagUrl = function (id)266
{267
var info = this.info(id);268
return 'images/flags/' + info.flag + '.svg';269
};270
271
I18n.togglePicker = function (force)272
{273
if (typeof force === 'boolean')274
{ this._pickerOpen = force; }275
else276
{ this._pickerOpen = !this._pickerOpen; }277
this.renderPicker();278
};279
280
I18n.renderPicker = function ()281
{282
if (typeof document === 'undefined')283
{ return; }284
var wrap = document.getElementById('lang-picker');285
var btn = document.getElementById('lang-current');286
var list = document.getElementById('lang-list');287
if (!wrap || !btn || !list)288
{ return; }289
var info = this.info();290
var img = btn.querySelector('img');291
if (img)292
{293
img.src = this.flagUrl(this.locale);294
img.alt = info.endonym;295
}296
btn.setAttribute('aria-label', this.t('lang.current', { name: info.endonym }));297
btn.setAttribute('aria-expanded', this._pickerOpen ? 'true' : 'false');298
btn.title = info.endonym;299
list.innerHTML = '';300
if (!this._pickerOpen)301
{302
list.hidden = true;303
wrap.classList.remove('open');304
return;305
}306
wrap.classList.add('open');307
list.hidden = false;308
for (var i = 0; i < this.LOCALES.length; i++)309
{310
var loc = this.LOCALES[i];311
var opt = document.createElement('button');312
opt.type = 'button';313
opt.className = 'lang-option' + (loc.id === this.locale ? ' current' : '');314
opt.setAttribute('data-locale', loc.id);315
opt.setAttribute('aria-label', loc.endonym);316
opt.title = loc.endonym;317
opt.innerHTML = '<img src="' + this.flagUrl(loc.id) + '" alt="" width="36" height="24">'318
+ '<span>' + loc.endonym + '</span>';319
(function (id)320
{321
opt.addEventListener('click', function (e)322
{323
e.stopPropagation();324
I18n.setLocale(id);325
I18n.togglePicker(false);326
});327
})(loc.id);328
list.appendChild(opt);329
}330
};331
332
I18n.bindPicker = function ()333
{334
if (typeof document === 'undefined')335
{ return; }336
var btn = document.getElementById('lang-current');337
var list = document.getElementById('lang-list');338
if (btn)339
{340
btn.addEventListener('click', function (e)341
{342
e.stopPropagation();343
I18n.togglePicker();344
});345
}346
document.addEventListener('click', function (e)347
{348
var wrap = document.getElementById('lang-picker');349
if (!wrap || !I18n._pickerOpen)350
{ return; }351
if (!wrap.contains(e.target))352
{ I18n.togglePicker(false); }353
});354
document.addEventListener('keydown', function (e)355
{356
if (e.key === 'Escape' && I18n._pickerOpen)357
{ I18n.togglePicker(false); }358
});359
this.renderPicker();360
};361
362
I18n.init = function ()363
{364
this._load();365
this.locale = this.readStored();366
if (typeof document !== 'undefined' && document.documentElement)367
{368
document.documentElement.lang = this.info().htmlLang;369
document.documentElement.setAttribute('data-locale', this.locale);370
}371
this.apply();372
};373
374
I18n.applyFromProfile = function (locale)375
{376
if (this.known(locale))377
{ this.setLocale(locale, { sync: false, persist: true }); }378
};379
380
if (typeof module !== 'undefined' && module.exports)381
{ module.exports = I18n; }382
else if (typeof globalThis !== 'undefined')383
{ globalThis.I18n = I18n; }@@ -0,0 +1,2105 @@
1
'use strict';
2
3
var App = {
4
screen: 'menu',
5
games: [],
6
game: null,
7
selected: null, // player id or 'self-move'
8
pollTimer: null,
9
tickTimer: null,
10
replay: null, // { events, index, timer, snapshot }
11
rulesDirty: false,
12
savingRules: false
13
};
14
15
function $(id)
16
{
17
return document.getElementById(id);
18
}
19
20
function showScreen(name)
21
{
22
['menu', 'lobby', 'game'].forEach(function (s)
23
{
24
var el = $(s);
25
if (el) { el.hidden = s !== name; }
26
});
27
App.screen = name;
28
$('top-bar').hidden = name !== 'game';
29
if (name !== 'game')
30
{ App.stopReplay(); }
31
}
32
33
function showError(id, err)
34
{
35
var el = $(id);
36
if (!el) { return; }
37
if (!err)
38
{
39
el.hidden = true;
40
el.textContent = '';
41
return;
42
}
43
var msg = err && (err.code || err.message) ? I18n.error(err.code || err.message) : String(err);
44
if (err && err.status)
45
{ msg = I18n.t('error.serverStatus', { status: err.status }); }
46
el.textContent = msg;
47
el.hidden = false;
48
}
49
50
function initials(name)
51
{
52
if (!name) { return '?'; }
53
var parts = String(name).trim().split(/\s+/);
54
var s = parts[0].charAt(0);
55
if (parts.length > 1)
56
{ s += parts[parts.length - 1].charAt(0); }
57
return s.toUpperCase();
58
}
59
60
function avatarNode(player, size, fixed)
61
{
62
size = size || 40;
63
var wrap = document.createElement('span');
64
wrap.className = 'avatar-wrap';
65
wrap.style.setProperty('--c', player.color || '#fff');
66
wrap.style.setProperty('--sz', size + 'px');
67
if (fixed)
68
{
69
wrap.classList.add('avatar-wrap-fixed');
70
wrap.style.width = size + 'px';
71
wrap.style.height = size + 'px';
72
}
73
function stylePiece(el)
74
{
75
el.className = (el.className ? el.className + ' ' : '') + 'piece' + (player.alive === false ? ' dead' : '');
76
if (fixed)
77
{
78
el.classList.add('piece-fixed');
79
el.style.width = size + 'px';
80
el.style.height = size + 'px';
81
el.style.borderColor = player.color || '#fff';
82
}
83
else
84
{
85
el.style.borderColor = player.color || '#fff';
86
}
87
}
88
if (player.avatar)
89
{
90
var img = document.createElement('img');
91
img.alt = player.name || '';
92
img.width = size;
93
img.height = size;
94
stylePiece(img);
95
img.src = player.avatar;
96
img.addEventListener('error', function ()
97
{
98
img.remove();
99
var fb = document.createElement('span');
100
fb.className = 'piece-initials';
101
stylePiece(fb);
102
fb.textContent = initials(player.name);
103
wrap.appendChild(fb);
104
});
105
wrap.appendChild(img);
106
}
107
else
108
{
109
var fb = document.createElement('span');
110
fb.className = 'piece-initials';
111
stylePiece(fb);
112
fb.textContent = initials(player.name);
113
wrap.appendChild(fb);
114
}
115
return wrap;
116
}
117
118
function findPlayer(id)
119
{
120
if (!App.game || !App.game.players) { return null; }
121
for (var i = 0; i < App.game.players.length; i++)
122
{
123
if (App.game.players[i].id === id)
124
{ return App.game.players[i]; }
125
}
126
return null;
127
}
128
129
function you()
130
{
131
return App.game ? findPlayer(App.game.you) : null;
132
}
133
134
/* ---------- init ---------- */
135
136
App.init = function ()
137
{
138
I18n.init();
139
I18n.bindPicker();
140
I18n.onChange(function ()
141
{
142
App.render();
143
});
144
this.bind();
145
this.localLinks();
146
var params = new URLSearchParams(location.search);
147
var join = params.get('join');
148
Api.loadMe().then(function (data)
149
{
150
if (data.locale)
151
{ I18n.applyFromProfile(data.locale); }
152
App.games = data.games || [];
153
App.renderMenu(data);
154
if (join)
155
{
156
if (!Api.me)
157
{
158
location.href = 'auth.php?next=' + encodeURIComponent('index.html?join=' + join);
159
return;
160
}
161
App.doJoin(join);
162
}
163
}).catch(function (err)
164
{
165
showError('menu-error', err);
166
App.renderMenu({});
167
});
168
this.tickTimer = setInterval(function () { App.tickClocks(); }, 250);
169
document.addEventListener('visibilitychange', function ()
170
{
171
if (document.hidden)
172
{
173
App.stopPoll();
174
}
175
else if (App.game && App.screen !== 'menu')
176
{
177
App.refreshFull();
178
App.startPoll();
179
}
180
});
181
};
182
183
App.localLinks = function ()
184
{
185
var span = $('local-links');
186
if (!span) { return; }
187
span.innerHTML = '';
188
for (var i = 1; i <= 8; i++)
189
{
190
if (i > 1) { span.appendChild(document.createTextNode(' · ')); }
191
var a = document.createElement('a');
192
a.href = 'auth.php?test=' + i;
193
a.textContent = 'test_user_' + i;
194
span.appendChild(a);
195
}
196
};
197
198
App.bind = function ()
199
{
200
$('btn-create').addEventListener('click', function () { App.createLobby(); });
201
$('join-form').addEventListener('submit', function (e)
202
{
203
e.preventDefault();
204
App.doJoin($('join-code').value);
205
});
206
$('lobby-back').addEventListener('click', function () { App.toMenu(); });
207
$('btn-copy').addEventListener('click', function () { App.copyInvite(); });
208
$('btn-start').addEventListener('click', function () { App.startGame(); });
209
$('btn-leave').addEventListener('click', function () { App.leaveLobby(); });
210
$('btn-upgrade').addEventListener('click', function () { App.act({ type: 'upgrade' }); });
211
$('btn-settings').addEventListener('click', function () { $('settings-panel').hidden = false; });
212
$('settings-close').addEventListener('click', function () { $('settings-panel').hidden = true; });
213
$('btn-to-menu').addEventListener('click', function ()
214
{
215
$('settings-panel').hidden = true;
216
App.toMenu();
217
});
218
$('btn-surrender').addEventListener('click', function () { App.confirmSurrender(); });
219
$('modal-close').addEventListener('click', function () { App.closeModal(); });
220
$('modal').addEventListener('click', function (e)
221
{
222
if (e.target === $('modal')) { App.closeModal(); }
223
});
224
$('sheet-close').addEventListener('click', function () { App.closeSheet(); });
225
$('sheet').addEventListener('click', function (e)
226
{
227
if (e.target === $('sheet')) { App.closeSheet(); }
228
});
229
$('tl-play').addEventListener('click', function () { App.toggleReplay(); });
230
$('tl-live').addEventListener('click', function () { App.jumpToPresent(); });
231
if ($('tl-back')) { $('tl-back').addEventListener('click', function () { App.stepReplay(-1); }); }
232
if ($('tl-fwd')) { $('tl-fwd').addEventListener('click', function () { App.stepReplay(1); }); }
233
this.bindTimelineScrub();
234
this.bindRuleEditors();
235
document.addEventListener('keydown', function (e)
236
{
237
if (e.key === 'Escape')
238
{
239
App.closeModal();
240
App.closeSheet();
241
$('settings-panel').hidden = true;
242
return;
243
}
244
App.onGameKey(e);
245
});
246
};
247
248
App.onGameKey = function (e)
249
{
250
if (App.screen !== 'game' || !App.game) { return; }
251
var t = e.target;
252
var tag = (t && t.tagName) ? t.tagName.toUpperCase() : '';
253
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable))
254
{ return; }
255
if (e.altKey || e.ctrlKey || e.metaKey) { return; }
256
if (e.key === 'ArrowLeft')
257
{
258
e.preventDefault();
259
App.stepReplay(-1);
260
}
261
else if (e.key === 'ArrowRight')
262
{
263
e.preventDefault();
264
App.stepReplay(1);
265
}
266
else if (e.key === ' ' || e.key === 'Spacebar' || e.code === 'Space')
267
{
268
e.preventDefault();
269
App.toggleReplay();
270
}
271
else if (e.key === 'End')
272
{
273
e.preventDefault();
274
App.jumpToPresent();
275
}
276
};
277
278
App.jumpToPresent = function ()
279
{
280
App.stopReplay();
281
if (App.game) { App.renderGame(); }
282
};
283
284
App.stepReplay = function (dir)
285
{
286
if (!App.game || App.game.status === 'lobby') { return; }
287
var n = this.spendEvents(App.game).length;
288
if (!n && dir) { return; }
289
var idx = App.replay ? App.replay.index : n;
290
var next = Math.max(0, Math.min(n, idx + dir));
291
if (App.replay && App.replay.timer)
292
{
293
clearInterval(App.replay.timer);
294
App.replay.timer = null;
295
}
296
if (next >= n)
297
{
298
this.jumpToPresent();
299
return;
300
}
301
this.jumpReplay(next, { animate: dir > 0 });
302
};
303
304
305
App.bindRuleEditors = function ()
306
{
307
['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'rule-ap-loot', 'rule-ap-time'].forEach(function (id)
308
{
309
if ($(id)) { $(id).addEventListener('change', function () { App.onRulesChange(); }); }
310
});
311
$('cf-add').addEventListener('click', function ()
312
{
313
var ranges = App.currentCfRanges();
314
ranges.push({ start: '22:00', end: '06:00' });
315
App.setCfRanges(ranges);
316
App.onRulesChange();
317
});
318
var vis = $('lobby-visibility');
319
if (vis)
320
{
321
vis.addEventListener('change', function () { App.onRulesChange(); });
322
}
323
};
324
325
App.visKeys = ['vis_shots', 'vis_gifts', 'vis_ap', 'vis_range', 'vis_lives'];
326
327
App.syncVisRadios = function (r, isHost)
328
{
329
App.visKeys.forEach(function (k)
330
{
331
var val = (r && r[k]) || 'public';
332
document.querySelectorAll('input[name="' + k + '"]').forEach(function (inp)
333
{
334
inp.checked = inp.value === val;
335
inp.disabled = !isHost;
336
});
337
});
338
};
339
340
App.readVisRules = function ()
341
{
342
var o = {};
343
App.visKeys.forEach(function (k)
344
{
345
var inp = document.querySelector('input[name="' + k + '"]:checked');
346
o[k] = inp ? inp.value : 'public';
347
});
348
return o;
349
};
350
351
App.render = function ()
352
{
353
I18n.apply();
354
I18n.renderPicker();
355
if (App.screen === 'menu') { App.renderMenu({ games: App.games, me: Api.me, configured: Api.configured, local: Api.local }); }
356
else if (App.screen === 'lobby') { App.renderLobby(); }
357
else if (App.screen === 'game') { App.renderGame(); }
358
};
359
360
/* ---------- menu ---------- */
361
362
App.renderMenu = function (data)
363
{
364
showScreen('menu');
365
App.stopPoll();
366
data = data || {};
367
var me = data.me !== undefined ? data.me : Api.me;
368
$('menu-guest').hidden = !!me;
369
$('menu-user').hidden = !me;
370
$('menu-guest-hint').hidden = !!me;
371
$('menu-actions').hidden = !me;
372
$('my-games').hidden = !me;
373
$('menu-unconfigured').hidden = !!Api.configured || !!Api.local;
374
$('menu-local-login').hidden = !Api.local;
375
if (me)
376
{
377
$('menu-name').textContent = me.name;
378
var av = $('menu-avatar');
379
if (me.avatar) { av.src = me.avatar; av.hidden = false; }
380
else { av.hidden = true; }
381
}
382
App.games = data.games || App.games || [];
383
var list = $('games-list');
384
list.innerHTML = '';
385
$('no-games').hidden = App.games.length > 0;
386
App.games.forEach(function (g)
387
{
388
var li = document.createElement('li');
389
var info = document.createElement('div');
390
info.style.flex = '1';
391
var st = g.status === 'lobby' ? I18n.t('menu.statusLobby')
392
: g.status === 'finished' ? I18n.t('menu.statusFinished')
393
: I18n.t('menu.statusRunning');
394
var sub = I18n.plural('lobby.playerCount', g.players);
395
if (g.status === 'finished')
396
{
397
if (g.draw) { sub = I18n.t('menu.draw'); }
398
else if (g.you_won) { sub = I18n.t('menu.youWon'); }
399
else
400
{
401
var w = (g.names || []).filter(function (p) { return p.id === g.winner_id; })[0];
402
sub = I18n.t('menu.winnerIs', { name: w ? w.name : '?' });
403
}
404
}
405
info.innerHTML = '<strong>' + st + '</strong> · <span class="mono">' + escapeHtml(g.code) + '</span><br><span class="hint">' + escapeHtml(sub) + '</span>';
406
var btn = document.createElement('button');
407
btn.type = 'button';
408
btn.textContent = I18n.t(g.status === 'finished' ? 'menu.open' : 'menu.continue');
409
btn.addEventListener('click', function () { App.openGame(g.id, g.status); });
410
li.appendChild(info);
411
li.appendChild(btn);
412
list.appendChild(li);
413
});
414
I18n.apply($('menu'));
415
};
416
417
App.toMenu = function ()
418
{
419
App.game = null;
420
App.selected = null;
421
App.stopPoll();
422
Api.games().then(function (data)
423
{
424
App.games = data.games || [];
425
App.renderMenu(data);
426
}).catch(function () { App.renderMenu({}); });
427
// clean join from URL
428
if (location.search)
429
{ history.replaceState({}, '', 'index.html'); }
430
};
431
432
App.createLobby = function ()
433
{
434
showError('menu-error');
435
Api.createLobby(Rules.defaultRules()).then(function (data)
436
{
437
App.enter(data.game);
438
}).catch(function (err) { showError('menu-error', err); });
439
};
440
441
App.doJoin = function (code)
442
{
443
showError('menu-error');
444
code = String(code || '').trim();
445
if (!code) { return; }
446
Api.join(code).then(function (data)
447
{
448
App.enter(data.game);
449
}).catch(function (err)
450
{
451
// Already a member of a game that has started: open it from the list.
452
if (err && err.code === 'game_started')
453
{
454
var want = String(code).toUpperCase();
455
var existing = (App.games || []).filter(function (g)
456
{
457
return String(g.code || '').toUpperCase() === want;
458
})[0];
459
if (existing)
460
{
461
App.openGame(existing.id, existing.status);
462
return;
463
}
464
}
465
showError('menu-error', err);
466
});
467
};
468
469
App.openGame = function (id, status)
470
{
471
Api.game(id).then(function (data)
472
{
473
App.enter(data.game);
474
}).catch(function (err) { showError('menu-error', err); });
475
};
476
477
App.enter = function (game)
478
{
479
App.game = game;
480
if (game.status === 'lobby')
481
{
482
showScreen('lobby');
483
App.renderLobby();
484
}
485
else
486
{
487
showScreen('game');
488
App.renderGame();
489
}
490
App.startPoll();
491
if (game && game.code)
492
{
493
history.replaceState({}, '', 'index.html?join=' + encodeURIComponent(game.code));
494
}
495
};
496
497
/* ---------- lobby ---------- */
498
499
App.renderLobby = function ()
500
{
501
var g = App.game;
502
if (!g) { return; }
503
$('lobby-code').textContent = g.code;
504
var url = location.origin + location.pathname.replace(/index\.html$/, '') + 'index.html?join=' + encodeURIComponent(g.code);
505
$('invite-link').value = url;
506
var isHost = g.host_id === g.you;
507
var list = $('lobby-players');
508
list.innerHTML = '';
509
(g.players || []).forEach(function (p)
510
{
511
var li = document.createElement('li');
512
li.appendChild(avatarNode(p, 40, true));
513
var name = document.createElement('span');
514
name.style.flex = '1';
515
name.textContent = p.name + (p.is_you ? ' (' + I18n.t('lobby.you') + ')' : '') + (p.is_host ? ' · ' + I18n.t('lobby.host') : '');
516
li.appendChild(name);
517
var dot = document.createElement('span');
518
dot.className = 'player-dot';
519
dot.style.background = p.color;
520
li.appendChild(dot);
521
list.appendChild(li);
522
});
523
var n = (g.players || []).length;
524
$('lobby-need').hidden = n >= 2;
525
$('btn-start').hidden = !isHost;
526
$('btn-start').disabled = n < 2;
527
$('lobby-waiting').hidden = isHost;
528
// Rules
529
var r = g.rules || Rules.defaultRules();
530
$('rule-jury').checked = !!r.jury;
531
if ($('rule-ap-loot')) { $('rule-ap-loot').checked = !!r.ap_loot; }
532
if ($('rule-ap-time')) { $('rule-ap-time').value = r.ap_time || '00:00'; }
533
$('rule-shrink').checked = !!r.shrinking_arena;
534
$('rule-shrink-days').value = r.shrink_interval_days || 7;
535
$('rule-ceasefire').checked = !!r.ceasefire;
536
$('shrink-days-wrap').hidden = !r.shrinking_arena;
537
$('ceasefire-editor').hidden = !r.ceasefire;
538
['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'cf-add', 'rule-ap-loot', 'rule-ap-time'].forEach(function (id)
539
{
540
if ($(id)) { $(id).disabled = !isHost; }
541
});
542
App.renderCfEditor(r.ceasefire_ranges || [], isHost);
543
App.syncVisRadios(r, isHost);
544
I18n.apply($('lobby'));
545
};
546
547
App.currentCfRanges = function ()
548
{
549
return (App.game && App.game.rules && App.game.rules.ceasefire_ranges) || [];
550
};
551
552
App.setCfRanges = function (ranges)
553
{
554
if (!App.game.rules) { App.game.rules = Rules.defaultRules(); }
555
App.game.rules.ceasefire_ranges = Rules.normalizeRanges(ranges);
556
App.renderCfEditor(App.game.rules.ceasefire_ranges, App.game.host_id === App.game.you);
557
};
558
559
App.renderCfEditor = function (ranges, editable)
560
{
561
CeasefireClock.render($('cf-clock'), ranges, {
562
editable: editable,
563
onChange: function (next)
564
{
565
App.setCfRanges(next);
566
App.onRulesChange();
567
}
568
});
569
var ul = $('cf-ranges');
570
ul.innerHTML = '';
571
if (!ranges.length)
572
{
573
var empty = document.createElement('li');
574
empty.className = 'hint';
575
empty.setAttribute('data-i18n', 'lobby.ceasefireEmpty');
576
empty.textContent = I18n.t('lobby.ceasefireEmpty');
577
ul.appendChild(empty);
578
return;
579
}
580
ranges.forEach(function (r, i)
581
{
582
var li = document.createElement('li');
583
var a = document.createElement('input');
584
a.type = 'time';
585
a.value = r.start;
586
a.setAttribute('aria-label', I18n.t('lobby.ceasefireStart'));
587
a.disabled = !editable;
588
var b = document.createElement('input');
589
b.type = 'time';
590
b.value = r.end;
591
b.setAttribute('aria-label', I18n.t('lobby.ceasefireEnd'));
592
b.disabled = !editable;
593
function commit()
594
{
595
var next = App.currentCfRanges().slice();
596
next[i] = { start: a.value, end: b.value };
597
App.setCfRanges(next);
598
App.onRulesChange();
599
}
600
a.addEventListener('change', commit);
601
b.addEventListener('change', commit);
602
var rm = document.createElement('button');
603
rm.type = 'button';
604
rm.className = 'btn-secondary';
605
rm.textContent = I18n.t('lobby.ceasefireRemove');
606
rm.disabled = !editable;
607
rm.addEventListener('click', function ()
608
{
609
var next = App.currentCfRanges().slice();
610
next.splice(i, 1);
611
App.setCfRanges(next);
612
App.onRulesChange();
613
});
614
li.appendChild(a);
615
li.appendChild(document.createTextNode('–'));
616
li.appendChild(b);
617
li.appendChild(rm);
618
ul.appendChild(li);
619
});
620
};
621
622
App.onRulesChange = function ()
623
{
624
if (!App.game || App.game.status !== 'lobby') { return; }
625
if (App.game.host_id !== App.game.you) { return; }
626
$('shrink-days-wrap').hidden = !$('rule-shrink').checked;
627
$('ceasefire-editor').hidden = !$('rule-ceasefire').checked;
628
var rules = {
629
jury: $('rule-jury').checked,
630
shrinking_arena: $('rule-shrink').checked,
631
shrink_interval_days: parseInt($('rule-shrink-days').value, 10) || 7,
632
ceasefire: $('rule-ceasefire').checked,
633
ceasefire_ranges: App.currentCfRanges(),
634
ap_loot: $('rule-ap-loot') ? $('rule-ap-loot').checked : false,
635
ap_time: ($('rule-ap-time') && $('rule-ap-time').value) ? $('rule-ap-time').value : '00:00'
636
};
637
Object.assign(rules, App.readVisRules());
638
App.game.rules = Object.assign({}, App.game.rules, rules);
639
App.rulesDirty = true;
640
if (App._rulesTimer) { clearTimeout(App._rulesTimer); }
641
App._rulesTimer = setTimeout(function ()
642
{
643
if (!App.rulesDirty) { return; }
644
App.rulesDirty = false;
645
Api.setRules(App.game.id, App.game.rules).then(function (data)
646
{
647
App.game = data.game;
648
App.renderLobby();
649
}).catch(function (err) { showError('lobby-error', err); });
650
}, 350);
651
};
652
653
App.copyInvite = function ()
654
{
655
var v = $('invite-link').value;
656
function ok()
657
{
658
$('copy-status').hidden = false;
659
setTimeout(function () { $('copy-status').hidden = true; }, 1500);
660
}
661
if (navigator.clipboard && navigator.clipboard.writeText)
662
{
663
navigator.clipboard.writeText(v).then(ok).catch(function ()
664
{
665
$('invite-link').select();
666
try { document.execCommand('copy'); ok(); } catch (e) {}
667
});
668
}
669
else
670
{
671
$('invite-link').select();
672
try { document.execCommand('copy'); ok(); } catch (e) {}
673
}
674
};
675
676
App.startGame = function ()
677
{
678
showError('lobby-error');
679
Api.start(App.game.id).then(function (data)
680
{
681
App.enter(data.game);
682
}).catch(function (err) { showError('lobby-error', err); });
683
};
684
685
App.leaveLobby = function ()
686
{
687
Api.leave(App.game.id).then(function () { App.toMenu(); })
688
.catch(function (err) { showError('lobby-error', err); });
689
};
690
691
/* ---------- game ---------- */
692
693
App.renderGame = function ()
694
{
695
var g = App.replay ? App.replay.view : App.game;
696
if (!g) { return; }
697
this.renderHud(g);
698
this.renderBoard(g);
699
this.renderJury(g);
700
this.renderTimeline(App.game); // ticks from the (already filtered) event list
701
this.tickClocks();
702
I18n.apply($('game'));
703
I18n.apply($('top-bar'));
704
if (!App.replay) { this.clearBoardFx(); }
705
};
706
707
App.renderHud = function (g)
708
{
709
var me = findIn(g.players, g.you) || you();
710
var stats = $('you-stats');
711
if (me)
712
{
713
stats.innerHTML = '<strong>' + escapeHtml(me.name) + '</strong> · '
714
+ I18n.t('game.lives') + ' <strong>' + me.lives + '</strong> · '
715
+ I18n.t('game.ap') + ' <strong>' + me.ap + '</strong> · '
716
+ I18n.t('game.range') + ' <strong>' + me.range + '</strong>';
717
}
718
var legal = g.legal || {};
719
$('btn-upgrade').hidden = !legal.upgrade;
720
$('btn-upgrade').disabled = !legal.upgrade;
721
$('day-label').textContent = I18n.t('game.day', { n: g.day || 0 });
722
var sb = $('shrink-banner');
723
if (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null)
724
{
725
sb.hidden = false;
726
if (g.shrink_in_days === 0) { sb.textContent = I18n.t('game.shrinkToday'); }
727
else if (g.shrink_in_days === 1) { sb.textContent = I18n.t('game.shrinkTomorrow'); }
728
else { sb.textContent = I18n.plural('game.shrinkInDays', g.shrink_in_days); }
729
}
730
else { sb.hidden = true; }
731
var banner = $('game-banner');
732
if (g.status === 'finished')
733
{
734
banner.hidden = false;
735
if (g.draw) { banner.textContent = I18n.t('game.draw'); }
736
else if (g.winner_id === g.you) { banner.textContent = I18n.t('game.youWin'); }
737
else
738
{
739
var w = findIn(g.players, g.winner_id);
740
banner.textContent = I18n.t('game.winner', { name: w ? w.name : '?' });
741
}
742
}
743
else if (me && !me.alive)
744
{
745
banner.hidden = false;
746
banner.textContent = I18n.t('game.spectating');
747
}
748
else { banner.hidden = true; }
749
};
750
751
function findIn(list, id)
752
{
753
if (!list) { return null; }
754
for (var i = 0; i < list.length; i++)
755
{
756
if (list[i].id === id) { return list[i]; }
757
}
758
return null;
759
}
760
761
App.renderBoard = function (g)
762
{
763
var board = $('board');
764
var size = g.grid || 6;
765
var inset = g.arena_inset || 0;
766
var nextInset = (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null && g.max_inset > inset)
767
? inset + 1 : null;
768
board.style.setProperty('--n', String(size));
769
board.style.gridTemplateColumns = 'repeat(' + size + ', 1fr)';
770
board.style.gridTemplateRows = 'repeat(' + size + ', 1fr)';
771
board.innerHTML = '';
772
var legal = (!App.replay && g.legal) ? g.legal : { move: [], shoot: [] };
773
var moveSet = {};
774
(legal.move || []).forEach(function (t) { moveSet[t.x + ',' + t.y] = true; });
775
var me = findIn(g.players, g.you);
776
var showMoves = App.selected && me && App.selected === me.id;
777
for (var y = 0; y < size; y++)
778
{
779
for (var x = 0; x < size; x++)
780
{
781
var cell = document.createElement('button');
782
cell.type = 'button';
783
cell.className = 'cell';
784
cell.setAttribute('role', 'gridcell');
785
cell.dataset.x = String(x);
786
cell.dataset.y = String(y);
787
var passable = Rules.isPassable(size, inset, x, y);
788
if (!passable)
789
{
790
cell.classList.add('impassable');
791
cell.disabled = true;
792
cell.title = I18n.t('game.impassable');
793
}
794
else if (nextInset != null && !Rules.isPassable(size, nextInset, x, y))
795
{
796
cell.classList.add('threat');
797
cell.title = I18n.t('game.willShrink');
798
}
799
if (showMoves && moveSet[x + ',' + y])
800
{ cell.classList.add('move-target'); }
801
var occupant = null;
802
(g.players || []).forEach(function (p)
803
{
804
if (p.x === x && p.y === y) { occupant = p; }
805
});
806
// Prefer living occupant if two (dead + living shouldn't share, but dead stay visually)
807
(g.players || []).forEach(function (p)
808
{
809
if (p.x === x && p.y === y && p.alive) { occupant = p; }
810
});
811
if (occupant)
812
{
813
var node = avatarNode(occupant, 48);
814
var pic = node.firstChild;
815
if (pic) { cell.appendChild(pic); }
816
if (App.selected === occupant.id) { cell.classList.add('selected'); }
817
if (!App.replay && legal.shoot && legal.shoot.indexOf(occupant.id) >= 0)
818
{ cell.classList.add('in-range'); }
819
}
820
(function (cx, cy, occ)
821
{
822
cell.addEventListener('click', function () { App.onCell(cx, cy, occ); });
823
})(x, y, occupant);
824
board.appendChild(cell);
825
}
826
}
827
};
828
829
App.onCell = function (x, y, occupant)
830
{
831
if (App.replay) { this.stopReplay(); }
832
var g = App.game;
833
if (!g || g.status !== 'running')
834
{
835
if (occupant) { this.openInfo(occupant); }
836
return;
837
}
838
var me = you();
839
var legal = g.legal || {};
840
// Move onto highlighted tile
841
if (me && App.selected === me.id && !occupant)
842
{
843
var ok = (legal.move || []).some(function (t) { return t.x === x && t.y === y; });
844
if (ok)
845
{
846
this.act({ type: 'move', x: x, y: y });
847
App.selected = null;
848
return;
849
}
850
}
851
if (occupant)
852
{
853
if (occupant.is_you || occupant.id === g.you)
854
{
855
App.selected = occupant.id;
856
this.renderGame();
857
return;
858
}
859
this.openPlayerOptions(occupant);
860
return;
861
}
862
App.selected = null;
863
this.renderGame();
864
};
865
866
App.openPlayerOptions = function (p)
867
{
868
App.selected = p.id;
869
this.renderGame();
870
var g = App.game;
871
var legal = g.legal || {};
872
var body = document.createElement('div');
873
body.className = 'opt-list';
874
function add(label, fn, disabled, reason)
875
{
876
var b = document.createElement('button');
877
b.type = 'button';
878
b.textContent = label;
879
if (disabled)
880
{
881
b.disabled = true;
882
if (reason) { b.title = reason; }
883
}
884
else
885
{
886
b.addEventListener('click', function () { App.closeSheet(); fn(); });
887
}
888
body.appendChild(b);
889
}
890
add(I18n.t('opt.info'), function () { App.openInfo(p); });
891
var canAttack = legal.shoot && legal.shoot.indexOf(p.id) >= 0;
892
var cfBlock = legal.ceasefire || (g.ceasefire && g.ceasefire.active);
893
add(I18n.t('opt.attack'), function () { App.act({ type: 'shoot', target: p.id }); },
894
!canAttack,
895
cfBlock ? I18n.t('game.attackDisabledReason') : (I18n.t('error.out_of_range')));
896
var canGive = legal.give && legal.give.indexOf(p.id) >= 0;
897
add(I18n.t('opt.give'), function () { App.openGive(p); }, !canGive);
898
add(I18n.t('opt.message'), function () { App.openChat(p); });
899
$('sheet-body').innerHTML = '';
900
var head = document.createElement('h2');
901
head.textContent = p.name;
902
$('sheet-body').appendChild(head);
903
$('sheet-body').appendChild(body);
904
$('sheet').hidden = false;
905
};
906
907
App.openInfo = function (p)
908
{
909
var body = document.createElement('div');
910
function stat(label, val)
911
{
912
var shown = (val == null) ? I18n.t('info.hidden') : String(val);
913
return '<p>' + label + ': <strong>' + shown + '</strong></p>';
914
}
915
body.innerHTML = stat(I18n.t('info.lives'), p.lives)
916
+ stat(I18n.t('info.ap'), p.ap)
917
+ stat(I18n.t('info.range'), p.range);
918
if (!p.alive)
919
{
920
body.innerHTML += '<p>' + I18n.t(p.surrendered ? 'game.surrendered' : 'game.dead') + '</p>';
921
}
922
var lab = document.createElement('label');
923
lab.textContent = I18n.t('info.notes');
924
var ta = document.createElement('textarea');
925
ta.rows = 5;
926
ta.value = p.note || '';
927
ta.setAttribute('maxlength', '2000');
928
var hint = document.createElement('p');
929
hint.className = 'hint';
930
hint.textContent = I18n.t('info.notesHint');
931
var save = document.createElement('button');
932
save.type = 'button';
933
save.textContent = I18n.t('info.saveNotes');
934
var st = document.createElement('span');
935
st.className = 'hint';
936
save.addEventListener('click', function ()
937
{
938
Api.note(App.game.id, p.id, ta.value).then(function (data)
939
{
940
App.game = data.game;
941
st.textContent = I18n.t('info.saved');
942
}).catch(function (err) { st.textContent = I18n.error(err.code || err.message); });
943
});
944
body.appendChild(lab);
945
body.appendChild(ta);
946
body.appendChild(hint);
947
body.appendChild(save);
948
body.appendChild(st);
949
App.openModal(I18n.t('info.title') + ' — ' + p.name, body);
950
};
951
952
App.openGive = function (p)
953
{
954
var me = you();
955
var max = me ? me.ap : 1;
956
var body = document.createElement('div');
957
var lab = document.createElement('label');
958
lab.textContent = I18n.t('give.howMany');
959
var inp = document.createElement('input');
960
inp.type = 'number';
961
inp.min = '1';
962
inp.max = String(max);
963
inp.value = '1';
964
inp.inputMode = 'numeric';
965
var have = document.createElement('p');
966
have.className = 'hint';
967
have.textContent = I18n.t('give.youHave', { n: max });
968
var btn = document.createElement('button');
969
btn.type = 'button';
970
btn.textContent = I18n.t('give.send');
971
btn.addEventListener('click', function ()
972
{
973
var n = parseInt(inp.value, 10);
974
App.closeModal();
975
App.act({ type: 'give', target: p.id, amount: n });
976
});
977
body.appendChild(lab);
978
body.appendChild(inp);
979
body.appendChild(have);
980
body.appendChild(btn);
981
App.openModal(I18n.t('give.title') + ' — ' + p.name, body);
982
};
983
984
App.openChat = function (p)
985
{
986
var body = document.createElement('div');
987
var log = document.createElement('div');
988
log.className = 'chat-log';
989
function fill(game)
990
{
991
log.innerHTML = '';
992
var msgs = (game.messages || []).filter(function (m)
993
{
994
return (m.from === p.id && m.to === game.you) || (m.to === p.id && m.from === game.you);
995
});
996
if (!msgs.length)
997
{
998
var em = document.createElement('p');
999
em.className = 'hint';
1000
em.textContent = I18n.t('chat.empty');
1001
log.appendChild(em);
1002
}
1003
msgs.forEach(function (m)
1004
{
1005
var b = document.createElement('div');
1006
b.className = 'chat-bubble' + (m.from === game.you ? ' mine' : '');
1007
b.textContent = m.text;
1008
log.appendChild(b);
1009
});
1010
log.scrollTop = log.scrollHeight;
1011
}
1012
fill(App.game);
1013
var row = document.createElement('form');
1014
row.className = 'chat-compose';
1015
row.action = '#';
1016
var inp = document.createElement('input');
1017
inp.type = 'text';
1018
inp.maxLength = 1000;
1019
inp.placeholder = I18n.t('chat.placeholder');
1020
inp.setAttribute('data-i18n-placeholder', 'chat.placeholder');
1021
var send = document.createElement('button');
1022
send.type = 'submit';
1023
send.textContent = I18n.t('chat.send');
1024
row.appendChild(inp);
1025
row.appendChild(send);
1026
row.addEventListener('submit', function (e)
1027
{
1028
e.preventDefault();
1029
var t = inp.value.trim();
1030
if (!t) { return; }
1031
inp.value = '';
1032
Api.message(App.game.id, p.id, t).then(function (data)
1033
{
1034
App.game = data.game;
1035
fill(App.game);
1036
}).catch(function (err) { showError('game-error', err); });
1037
});
1038
body.appendChild(log);
1039
body.appendChild(row);
1040
App.openModal(I18n.t('chat.title', { name: p.name }), body);
1041
// Keep a hook so polls refresh an open chat
1042
App._openChat = { id: p.id, fill: fill };
1043
inp.focus();
1044
};
1045
1046
App.openModal = function (title, body)
1047
{
1048
$('modal-title').textContent = title;
1049
$('modal-body').innerHTML = '';
1050
$('modal-body').appendChild(body);
1051
$('modal').hidden = false;
1052
};
1053
1054
App.closeModal = function ()
1055
{
1056
$('modal').hidden = true;
1057
App._openChat = null;
1058
};
1059
1060
App.closeSheet = function ()
1061
{
1062
$('sheet').hidden = true;
1063
};
1064
1065
App.renderJury = function (g)
1066
{
1067
var panel = $('jury-panel');
1068
var legal = g.legal || {};
1069
if (App.replay || !legal.vote)
1070
{
1071
panel.hidden = true;
1072
return;
1073
}
1074
panel.hidden = false;
1075
var ul = $('jury-list');
1076
ul.innerHTML = '';
1077
legal.vote.forEach(function (id)
1078
{
1079
var p = findIn(g.players, id);
1080
if (!p) { return; }
1081
var li = document.createElement('li');
1082
li.appendChild(avatarNode(p, 32, true));
1083
var n = document.createElement('span');
1084
n.style.flex = '1';
1085
n.textContent = p.name;
1086
li.appendChild(n);
1087
var b = document.createElement('button');
1088
b.type = 'button';
1089
if (legal.my_vote === id)
1090
{
1091
b.textContent = I18n.t('jury.votedFor', { name: p.name });
1092
b.disabled = true;
1093
}
1094
else
1095
{
1096
b.textContent = legal.my_vote ? I18n.t('jury.change') : I18n.t('jury.vote');
1097
b.addEventListener('click', function () { App.act({ type: 'vote', target: id }); });
1098
}
1099
li.appendChild(b);
1100
ul.appendChild(li);
1101
});
1102
};
1103
1104
App.confirmSurrender = function ()
1105
{
1106
$('settings-panel').hidden = true;
1107
var body = document.createElement('div');
1108
var p = document.createElement('p');
1109
p.textContent = I18n.t('game.surrenderConfirm');
1110
var yes = document.createElement('button');
1111
yes.type = 'button';
1112
yes.className = 'btn-danger';
1113
yes.textContent = I18n.t('game.surrenderConfirmBtn');
1114
yes.addEventListener('click', function ()
1115
{
1116
App.closeModal();
1117
App.act({ type: 'surrender' });
1118
});
1119
var no = document.createElement('button');
1120
no.type = 'button';
1121
no.className = 'btn-secondary';
1122
no.textContent = I18n.t('game.surrenderCancel');
1123
no.addEventListener('click', function () { App.closeModal(); });
1124
body.appendChild(p);
1125
body.appendChild(yes);
1126
body.appendChild(document.createTextNode(' '));
1127
body.appendChild(no);
1128
App.openModal(I18n.t('game.surrender'), body);
1129
};
1130
1131
App.act = function (action)
1132
{
1133
showError('game-error');
1134
Api.act(App.game.id, action).then(function (data)
1135
{
1136
App.game = data.game;
1137
App.selected = action.type === 'move' ? null : App.selected;
1138
App.renderGame();
1139
}).catch(function (err) { showError('game-error', err); });
1140
};
1141
1142
/* ---------- clocks & polling ---------- */
1143
1144
App.tickClocks = function ()
1145
{
1146
if (App.screen !== 'game' || !App.game) { return; }
1147
var now = Api.now();
1148
var next = App.game.next_distribution_at;
1149
if (next && App.game.status === 'running')
1150
{
1151
$('ap-hms').textContent = Rules.formatHms(next - now);
1152
$('ap-countdown').hidden = false;
1153
}
1154
else
1155
{
1156
$('ap-countdown').hidden = App.game.status !== 'running';
1157
if (App.game.status !== 'running') { $('ap-hms').textContent = '00:00:00'; }
1158
}
1159
var cf = App.game.ceasefire;
1160
var box = $('cf-countdown');
1161
if (cf && cf.enabled && cf.until && App.game.status === 'running')
1162
{
1163
box.hidden = false;
1164
box.classList.toggle('active', !!cf.active);
1165
$('cf-label').textContent = I18n.t(cf.active ? 'game.ceasefireLeft' : 'game.ceasefireUntil');
1166
$('cf-hms').textContent = Rules.formatHms(cf.until - now);
1167
}
1168
else { box.hidden = true; }
1169
};
1170
1171
App.startPoll = function ()
1172
{
1173
this.stopPoll();
1174
this.pollTimer = setInterval(function () { App.poll(); }, 3000);
1175
};
1176
1177
App.stopPoll = function ()
1178
{
1179
if (this.pollTimer)
1180
{
1181
clearInterval(this.pollTimer);
1182
this.pollTimer = null;
1183
}
1184
};
1185
1186
App.poll = function ()
1187
{
1188
if (document.hidden || !App.game) { return; }
1189
var id = App.game.id;
1190
var v = App.game.version || 0;
1191
Api.sync(id, v).then(function (data)
1192
{
1193
if (!App.game || App.game.id !== id) { return; }
1194
if (data.next_distribution_at != null)
1195
{ App.game.next_distribution_at = data.next_distribution_at; }
1196
if (data.ceasefire !== undefined)
1197
{ App.game.ceasefire = data.ceasefire; }
1198
if (data.server_now) { /* Api already stored */ }
1199
if (data.changed && data.game)
1200
{
1201
var stayOn = App._openChat && App._openChat.id;
1202
App.game = data.game;
1203
if (App.screen === 'lobby' && data.game.status === 'lobby')
1204
{ App.renderLobby(); }
1205
else if (data.game.status !== 'lobby')
1206
{
1207
if (App.screen !== 'game') { showScreen('game'); }
1208
if (!App.replay) { App.renderGame(); }
1209
else { App.renderTimeline(App.game); }
1210
}
1211
if (stayOn && App._openChat)
1212
{ App._openChat.fill(App.game); }
1213
}
1214
App.tickClocks();
1215
}).catch(function () { /* transient; next poll retries */ });
1216
};
1217
1218
App.refreshFull = function ()
1219
{
1220
if (!App.game) { return; }
1221
var id = App.game.id;
1222
Api.game(id).then(function (data)
1223
{
1224
if (!App.game || App.game.id !== id) { return; }
1225
App.game = data.game;
1226
if (data.game.status === 'lobby') { App.renderLobby(); }
1227
else { App.renderGame(); }
1228
if (App._openChat) { App._openChat.fill(App.game); }
1229
}).catch(function () {});
1230
};
1231
1232
/* ---------- timeline ---------- */
1233
1234
App.spendEvents = function (game)
1235
{
1236
return (game.events || []).filter(function (e) { return e.spend; });
1237
};
1238
1239
App.renderTimeline = function (game)
1240
{
1241
var spends = this.spendEvents(game);
1242
var track = $('tl-track');
1243
var ticks = $('tl-ticks');
1244
ticks.innerHTML = '';
1245
var n = spends.length;
1246
track.setAttribute('aria-valuemax', String(Math.max(n, 0)));
1247
spends.forEach(function (e, i)
1248
{
1249
var t = document.createElement('div');
1250
t.className = 'tl-tick';
1251
// Align with playhead: spend i is at index i+1, position (i+1)/n.
1252
t.style.left = ((n <= 0 ? 0 : (i + 1) / n) * 100) + '%';
1253
ticks.appendChild(t);
1254
});
1255
var idx = App.replay ? App.replay.index : n;
1256
this.setPlayhead(idx, n);
1257
$('tl-play').textContent = (App.replay && App.replay.timer) ? '❚❚' : '▶';
1258
$('tl-play').title = I18n.t((App.replay && App.replay.timer) ? 'timeline.pause' : 'timeline.play');
1259
this.setCaption();
1260
track.setAttribute('aria-valuetext', idx + ' / ' + n);
1261
};
1262
1263
App.setPlayhead = function (idx, n)
1264
{
1265
var head = $('tl-head');
1266
if (n <= 0)
1267
{ head.style.left = '0%'; }
1268
else if (n === 1)
1269
{ head.style.left = (idx <= 0 ? '0%' : '100%'); }
1270
else
1271
{ head.style.left = (Math.max(0, Math.min(n, idx)) / n) * 100 + '%'; }
1272
$('tl-track').setAttribute('aria-valuenow', String(idx));
1273
};
1274
1275
App.setCaption = function ()
1276
{
1277
// No direct text log: events are shown only as playback visuals.
1278
var el = $('tl-caption');
1279
if (el)
1280
{
1281
el.hidden = true;
1282
el.textContent = '';
1283
}
1284
};
1285
1286
App.eventLabel = function (ev, game)
1287
{
1288
function name(id)
1289
{
1290
var p = findIn(game.players, id);
1291
return p ? p.name : (id || '');
1292
}
1293
switch (ev.type)
1294
{
1295
case 'start': return I18n.t('timeline.event.start');
1296
case 'move': return I18n.t('timeline.event.move', { name: name(ev.player) });
1297
case 'shoot': return I18n.t('timeline.event.shoot', { name: name(ev.player), target: name(ev.target) });
1298
case 'give': return I18n.t('timeline.event.give', { name: name(ev.player), target: name(ev.target), n: ev.amount });
1299
case 'upgrade': return I18n.t('timeline.event.upgrade', { name: name(ev.player), n: ev.range });
1300
case 'surrender': return I18n.t('timeline.event.surrender', { name: name(ev.player) });
1301
case 'daily':
1302
var s = I18n.t('timeline.event.daily', { n: ev.day });
1303
if (ev.jury && ev.jury.winners && ev.jury.winners.length)
1304
{
1305
var names = ev.jury.winners.map(name);
1306
s += ' — ' + (names.length === 1
1307
? I18n.t('timeline.event.jury', { name: names[0] })
1308
: I18n.t('timeline.event.juryTie', { names: names.join(', ') }));
1309
}
1310
return s;
1311
case 'shrink': return I18n.t('timeline.event.shrink');
1312
case 'win': return I18n.t('timeline.event.win', { name: name(ev.player) });
1313
case 'draw': return I18n.t('timeline.event.draw');
1314
case 'death':
1315
if (ev.cause === 'shot') { return I18n.t('timeline.event.deathShot', { name: name(ev.player), by: name(ev.by) }); }
1316
if (ev.cause === 'shrink') { return I18n.t('timeline.event.deathShrink', { name: name(ev.player) }); }
1317
if (ev.cause === 'crushed') { return I18n.t('timeline.event.deathCrushed', { name: name(ev.player) }); }
1318
return I18n.t('timeline.event.death', { name: name(ev.player) });
1319
default: return ev.type;
1320
}
1321
};
1322
1323
App.bindTimelineScrub = function ()
1324
{
1325
var track = $('tl-track');
1326
var dragging = false;
1327
function clientX(ev)
1328
{
1329
if (ev.clientX != null && ev.clientX !== 0) { return ev.clientX; }
1330
if (ev.touches && ev.touches[0]) { return ev.touches[0].clientX; }
1331
if (ev.changedTouches && ev.changedTouches[0]) { return ev.changedTouches[0].clientX; }
1332
return ev.clientX;
1333
}
1334
function pos(ev)
1335
{
1336
var r = track.getBoundingClientRect();
1337
var x = clientX(ev) - r.left;
1338
var t = r.width <= 0 ? 0 : x / r.width;
1339
var n = App.spendEvents(App.game).length;
1340
return Rules.timelineIndex(t, n);
1341
}
1342
function go(ev, scrub)
1343
{
1344
if (!App.game) { return; }
1345
// Click/tap: jump to the nearest event. Drag: scrub through them.
1346
App.jumpReplay(pos(ev), { animate: false, scrub: !!scrub });
1347
}
1348
function down(e)
1349
{
1350
if (e.button != null && e.button !== 0) { return; }
1351
dragging = true;
1352
if (track.setPointerCapture && e.pointerId != null)
1353
{
1354
try { track.setPointerCapture(e.pointerId); } catch (err) {}
1355
}
1356
if (e.preventDefault) { e.preventDefault(); }
1357
go(e, false);
1358
}
1359
function move(e)
1360
{
1361
if (!dragging) { return; }
1362
if (e.preventDefault) { e.preventDefault(); }
1363
go(e, true);
1364
}
1365
function up() { dragging = false; }
1366
track.addEventListener('pointerdown', down);
1367
track.addEventListener('pointermove', move);
1368
track.addEventListener('pointerup', up);
1369
track.addEventListener('pointercancel', up);
1370
// Fallback for older browsers / mixed input: same handlers on touch.
1371
track.addEventListener('touchstart', down, { passive: false });
1372
track.addEventListener('touchmove', move, { passive: false });
1373
track.addEventListener('touchend', up);
1374
track.addEventListener('touchcancel', up);
1375
};
1376
1377
App.toggleReplay = function ()
1378
{
1379
if (App.replay && App.replay.timer)
1380
{
1381
clearInterval(App.replay.timer);
1382
App.replay.timer = null;
1383
this.renderTimeline(App.game);
1384
return;
1385
}
1386
var n = this.spendEvents(App.game).length;
1387
if (!n) { return; }
1388
var startAt = (App.replay && App.replay.index < n) ? App.replay.index : 0;
1389
this.jumpReplay(startAt);
1390
App.replay.timer = setInterval(function ()
1391
{
1392
if (!App.replay) { return; }
1393
if (App.replay.index >= n)
1394
{
1395
App.stopReplay();
1396
return;
1397
}
1398
App.jumpReplay(App.replay.index + 1);
1399
}, 500);
1400
this.renderTimeline(App.game);
1401
};
1402
1403
App.jumpReplay = function (index, opts)
1404
{
1405
opts = opts || {};
1406
var game = App.game;
1407
var spends = this.spendEvents(game);
1408
var n = spends.length;
1409
index = Math.max(0, Math.min(n, index));
1410
var prev = App.replay && App.replay.view;
1411
var prevIndex = App.replay ? App.replay.index : null;
1412
var view = this.viewAtSpend(game, index);
1413
if (!App.replay) { App.replay = { timer: null }; }
1414
var stepping = prevIndex != null && index === prevIndex + 1;
1415
var animate = opts.animate !== false && (opts.animate || (App.replay.timer && stepping));
1416
App.replay.index = index;
1417
App.replay.view = view;
1418
this.renderBoard(view);
1419
this.renderHud(view);
1420
this.renderJury(view);
1421
this.renderTimeline(game);
1422
this.setCaption();
1423
var ev = index > 0 ? spends[index - 1] : null;
1424
this.playBoardFx(view, ev, prev, !!animate);
1425
};
1426
1427
App.viewAtSpend = function (game, spendCount)
1428
{
1429
// Walk a shallow clone of players from the start event / initial, applying
1430
// events until `spendCount` spend-ticks have been applied.
1431
var players = (game.players || []).map(function (p)
1432
{
1433
return Object.assign({}, p);
1434
});
1435
// Remember which numeric stats the server hid from this viewer, so replay
1436
// never invents values the live state would not show.
1437
var hidden = {};
1438
players.forEach(function (p)
1439
{
1440
hidden[p.id] = { lives: p.lives == null, ap: p.ap == null, range: p.range == null };
1441
});
1442
var events = game.events || [];
1443
var applied = 0;
1444
var start = events.filter(function (e) { return e.type === 'start'; })[0];
1445
if (start && start.players)
1446
{
1447
start.players.forEach(function (sp)
1448
{
1449
players.forEach(function (p)
1450
{
1451
if (p.id === sp.id)
1452
{
1453
p.x = sp.x; p.y = sp.y;
1454
if (!hidden[p.id] || !hidden[p.id].lives) { p.lives = 3; }
1455
if (!hidden[p.id] || !hidden[p.id].ap) { p.ap = 1; }
1456
if (!hidden[p.id] || !hidden[p.id].range) { p.range = 2; }
1457
p.alive = true; p.surrendered = false;
1458
}
1459
});
1460
});
1461
}
1462
var inset = 0;
1463
var day = 0;
1464
function apply(ev)
1465
{
1466
var p;
1467
if (ev.type === 'move')
1468
{
1469
p = findIn(players, ev.player);
1470
if (p && ev.to) { p.x = ev.to.x; p.y = ev.to.y; if (p.ap > 0) { p.ap--; } }
1471
}
1472
else if (ev.type === 'shoot')
1473
{
1474
p = findIn(players, ev.player);
1475
if (p && p.ap != null && p.ap > 0) { p.ap--; }
1476
var t = findIn(players, ev.target);
1477
if (t)
1478
{
1479
if (ev.lives_left != null && t.lives != null) { t.lives = ev.lives_left; }
1480
if (ev.killed)
1481
{
1482
t.alive = false;
1483
if (t.ap != null) { t.ap = 0; }
1484
if (t.lives != null) { t.lives = 0; }
1485
}
1486
}
1487
}
1488
else if (ev.type === 'give')
1489
{
1490
p = ev.player ? findIn(players, ev.player) : null;
1491
var t2 = findIn(players, ev.target);
1492
if (p && p.ap != null) { p.ap = Math.max(0, p.ap - (ev.amount || 1)); }
1493
if (t2 && t2.ap != null) { t2.ap += (ev.amount || 1); }
1494
}
1495
else if (ev.type === 'upgrade')
1496
{
1497
p = findIn(players, ev.player);
1498
if (p)
1499
{
1500
if (p.range != null && ev.range != null) { p.range = ev.range; }
1501
if (p.ap != null && p.ap > 0) { p.ap--; }
1502
}
1503
}
1504
else if (ev.type === 'surrender')
1505
{
1506
p = findIn(players, ev.player);
1507
if (p) { p.alive = false; p.surrendered = true; p.lives = 0; p.ap = 0; }
1508
}
1509
else if (ev.type === 'daily' && ev.grants)
1510
{
1511
day = ev.day || day;
1512
players.forEach(function (pl)
1513
{
1514
if (ev.grants[pl.id]) { pl.ap += ev.grants[pl.id]; }
1515
});
1516
}
1517
else if (ev.type === 'shrink')
1518
{
1519
inset = ev.inset || inset;
1520
(ev.moved || []).forEach(function (m)
1521
{
1522
var q = findIn(players, m.id);
1523
if (q && m.to) { q.x = m.to.x; q.y = m.to.y; if (q.lives > 0 && ev.hurt && ev.hurt.indexOf(m.id) >= 0) { /* already in lives? */ } }
1524
});
1525
(ev.hurt || []).forEach(function (id)
1526
{
1527
var q = findIn(players, id);
1528
if (q && ev.killed && ev.killed.indexOf(id) < 0 && q.lives > 0) { q.lives = Math.max(1, q.lives); }
1529
});
1530
(ev.killed || []).forEach(function (id)
1531
{
1532
var q = findIn(players, id);
1533
if (q) { q.alive = false; q.lives = 0; q.ap = 0; }
1534
});
1535
}
1536
}
1537
for (var i = 0; i < events.length; i++)
1538
{
1539
var ev = events[i];
1540
if (ev.spend)
1541
{
1542
if (applied >= spendCount) { break; }
1543
apply(ev);
1544
applied++;
1545
}
1546
else
1547
{
1548
// Apply non-spend events that occurred before this point (start,
1549
// daily, shrink, death) — only those before the next unapplied spend.
1550
// If we have already reached the target spend count, stop before later dailies.
1551
if (applied >= spendCount && ev.type !== 'start') { continue; }
1552
apply(ev);
1553
}
1554
}
1555
players.forEach(function (p)
1556
{
1557
var h = hidden[p.id];
1558
if (!h) { return; }
1559
if (h.lives) { p.lives = null; }
1560
if (h.ap) { p.ap = null; }
1561
if (h.range) { p.range = null; }
1562
});
1563
return {
1564
you: game.you,
1565
players: players,
1566
grid: game.grid,
1567
arena_inset: inset,
1568
max_inset: game.max_inset,
1569
shrink_in_days: null,
1570
rules: game.rules,
1571
legal: { move: [], shoot: [], give: [], upgrade: false, vote: null },
1572
day: day,
1573
status: game.status,
1574
winner_id: null,
1575
draw: false,
1576
next_distribution_at: null,
1577
ceasefire: null
1578
};
1579
};
1580
1581
App.stopReplay = function ()
1582
{
1583
if (App.replay && App.replay.timer)
1584
{ clearInterval(App.replay.timer); }
1585
App.replay = null;
1586
this.clearBoardFx();
1587
if (App.game && App.screen === 'game')
1588
{
1589
this.renderGame();
1590
}
1591
};
1592
1593
App.clearBoardFx = function ()
1594
{
1595
var fx = $('board-fx');
1596
if (fx) { fx.innerHTML = ''; }
1597
var wrap = $('board-wrap');
1598
if (wrap)
1599
{
1600
wrap.querySelectorAll('.fx-float').forEach(function (n) { n.remove(); });
1601
}
1602
document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse, #board .piece-initials.moving, #board .piece-initials.range-pulse').forEach(function (el)
1603
{
1604
el.classList.remove('moving', 'range-pulse');
1605
el.style.transform = '';
1606
el.style.transition = '';
1607
});
1608
};
1609
1610
App.cellCenter = function (x, y)
1611
{
1612
var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');
1613
var wrap = $('board-wrap');
1614
if (!cell || !wrap) { return null; }
1615
var wr = wrap.getBoundingClientRect();
1616
var r = cell.getBoundingClientRect();
1617
return {
1618
x: r.left + r.width / 2 - wr.left,
1619
y: r.top + r.height / 2 - wr.top,
1620
s: Math.min(r.width, r.height)
1621
};
1622
};
1623
1624
App.playerCell = function (view, id)
1625
{
1626
var p = findIn(view && view.players, id);
1627
if (!p) { return null; }
1628
return App.cellCenter(p.x, p.y);
1629
};
1630
1631
App.pieceInCell = function (x, y)
1632
{
1633
var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');
1634
return cell ? cell.querySelector('.piece, .piece-initials') : null;
1635
};
1636
1637
App.playBoardFx = function (view, ev, prev, animate)
1638
{
1639
this.clearBoardFx();
1640
if (!ev || !view) { return; }
1641
var wrap = $('board-wrap');
1642
var fx = $('board-fx');
1643
if (!wrap || !fx) { return; }
1644
fx.setAttribute('width', String(wrap.clientWidth));
1645
fx.setAttribute('height', String(wrap.clientHeight));
1646
fx.setAttribute('viewBox', '0 0 ' + wrap.clientWidth + ' ' + wrap.clientHeight);
1647
1648
if (ev.type === 'shoot' && ev.target)
1649
{
1650
var from = ev.player ? App.playerCell(prev || view, ev.player) : null;
1651
var to = App.playerCell(view, ev.target);
1652
// If the shooter is known (not filtered), draw a red arrow; the number
1653
// is damage, not remaining lives, so it does not leak hidden life totals.
1654
if (from && to && ev.player)
1655
{
1656
App.drawArrow(from, to, '#e85d5d', ev.damage != null ? ev.damage : 1);
1657
}
1658
else if (to)
1659
{
1660
App.floatNumber(to, ev.damage != null ? ev.damage : 1, '#e85d5d');
1661
}
1662
if (ev.loot && ev.player)
1663
{
1664
var lootAt = App.playerCell(view, ev.player);
1665
if (lootAt) { App.floatNumber(lootAt, '+' + ev.loot, '#4ecb8d'); }
1666
}
1667
}
1668
else if (ev.type === 'give')
1669
{
1670
var tTo = ev.target ? App.playerCell(view, ev.target) : null;
1671
var amount = ev.amount != null ? ev.amount : 1;
1672
if (ev.anonymous || !ev.player)
1673
{
1674
// Must not reveal the giver: show the AP gain on the recipient only,
1675
// with no source arrow (an arrow "from nowhere" would still suggest a direction).
1676
if (tTo) { App.floatNumber(tTo, '+' + amount, '#4ecb8d'); }
1677
}
1678
else
1679
{
1680
var gFrom = App.playerCell(prev || view, ev.player);
1681
if (gFrom && tTo)
1682
{
1683
App.drawArrow(gFrom, tTo, '#4ecb8d', amount);
1684
}
1685
else if (tTo)
1686
{
1687
App.floatNumber(tTo, '+' + amount, '#4ecb8d');
1688
}
1689
}
1690
}
1691
else if (ev.type === 'move' && ev.to && ev.from && ev.player && animate)
1692
{
1693
App.animateMove(ev.from, ev.to);
1694
}
1695
else if (ev.type === 'upgrade' && ev.player)
1696
{
1697
var p = findIn(view.players, ev.player);
1698
if (p)
1699
{
1700
var piece = App.pieceInCell(p.x, p.y);
1701
if (piece)
1702
{
1703
piece.classList.remove('range-pulse');
1704
void piece.offsetWidth;
1705
piece.classList.add('range-pulse');
1706
}
1707
}
1708
}
1709
};
1710
1711
App.drawArrow = function (from, to, color, number)
1712
{
1713
var fx = $('board-fx');
1714
if (!fx || !from || !to) { return; }
1715
var ns = 'http://www.w3.org/2000/svg';
1716
var dx = to.x - from.x, dy = to.y - from.y;
1717
var len = Math.sqrt(dx * dx + dy * dy) || 1;
1718
var ux = dx / len, uy = dy / len;
1719
var inset = Math.min(from.s || 24, to.s || 24) * 0.38;
1720
if (inset * 2 >= len) { inset = len * 0.22; }
1721
var x1 = from.x + ux * inset, y1 = from.y + uy * inset;
1722
var x2 = to.x - ux * inset, y2 = to.y - uy * inset;
1723
var mid = 'm' + Math.round(x1) + '-' + Math.round(y1) + '-' + Math.round(x2) + '-' + Math.round(y2);
1724
var defs = document.createElementNS(ns, 'defs');
1725
var marker = document.createElementNS(ns, 'marker');
1726
marker.setAttribute('id', mid);
1727
marker.setAttribute('viewBox', '0 0 10 10');
1728
marker.setAttribute('refX', '8');
1729
marker.setAttribute('refY', '5');
1730
marker.setAttribute('markerWidth', '7');
1731
marker.setAttribute('markerHeight', '7');
1732
marker.setAttribute('orient', 'auto');
1733
var tip = document.createElementNS(ns, 'path');
1734
tip.setAttribute('d', 'M 0 0 L 10 5 L 0 10 z');
1735
tip.setAttribute('fill', color);
1736
marker.appendChild(tip);
1737
defs.appendChild(marker);
1738
fx.appendChild(defs);
1739
var line = document.createElementNS(ns, 'line');
1740
line.setAttribute('x1', String(x1));
1741
line.setAttribute('y1', String(y1));
1742
line.setAttribute('x2', String(x2));
1743
line.setAttribute('y2', String(y2));
1744
line.setAttribute('stroke', color);
1745
line.setAttribute('stroke-width', '4');
1746
line.setAttribute('stroke-linecap', 'round');
1747
line.setAttribute('marker-end', 'url(#' + mid + ')');
1748
fx.appendChild(line);
1749
if (number != null && number !== '')
1750
{
1751
var mx = x1 + (x2 - x1) * 0.55;
1752
var my = y1 + (y2 - y1) * 0.55;
1753
var circ = document.createElementNS(ns, 'circle');
1754
circ.setAttribute('cx', String(mx));
1755
circ.setAttribute('cy', String(my));
1756
circ.setAttribute('r', '13');
1757
circ.setAttribute('fill', color);
1758
circ.setAttribute('stroke', '#0c1020');
1759
circ.setAttribute('stroke-width', '2');
1760
fx.appendChild(circ);
1761
var tx = document.createElementNS(ns, 'text');
1762
tx.setAttribute('x', String(mx));
1763
tx.setAttribute('y', String(my + 1));
1764
tx.setAttribute('text-anchor', 'middle');
1765
tx.setAttribute('dominant-baseline', 'middle');
1766
tx.setAttribute('fill', '#fff');
1767
tx.setAttribute('font-size', '13');
1768
tx.setAttribute('font-weight', '700');
1769
tx.setAttribute('font-family', 'ui-sans-serif, system-ui, sans-serif');
1770
tx.textContent = String(number);
1771
fx.appendChild(tx);
1772
}
1773
};
1774
1775
App.floatNumber = function (at, text, color)
1776
{
1777
var wrap = $('board-wrap');
1778
if (!wrap || !at) { return; }
1779
var el = document.createElement('div');
1780
el.className = 'fx-float';
1781
el.textContent = String(text);
1782
el.style.left = at.x + 'px';
1783
el.style.top = at.y + 'px';
1784
if (color) { el.style.color = color; }
1785
wrap.appendChild(el);
1786
};
1787
1788
App.animateMove = function (from, to)
1789
{
1790
var piece = App.pieceInCell(to.x, to.y);
1791
var a = App.cellCenter(from.x, from.y);
1792
var b = App.cellCenter(to.x, to.y);
1793
if (!piece || !a || !b) { return; }
1794
var dx = a.x - b.x, dy = a.y - b.y;
1795
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) { return; }
1796
piece.classList.add('moving');
1797
piece.style.transition = 'none';
1798
piece.style.transform = 'translate(' + dx + 'px, ' + dy + 'px)';
1799
requestAnimationFrame(function ()
1800
{
1801
requestAnimationFrame(function ()
1802
{
1803
piece.style.transition = 'transform 0.4s ease';
1804
piece.style.transform = 'translate(0, 0)';
1805
});
1806
});
1807
};
1808
1809
1810
function escapeHtml(s)
1811
{
1812
return String(s).replace(/[&<>"']/g, function (c)
1813
{
1814
return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c];
1815
});
1816
}
1817
1818
/* ---------- 24-hour cease-fire clock ---------- */
1819
1820
var CeasefireClock = {
1821
size: 320,
1822
cx: 160,
1823
cy: 160,
1824
r: 128
1825
};
1826
1827
CeasefireClock.minsToAngle = function (mins)
1828
{
1829
// 0 at top, clockwise, 1440 minutes = 360°.
1830
return (mins / 1440) * 2 * Math.PI - Math.PI / 2;
1831
};
1832
1833
CeasefireClock.angleToMins = function (ang)
1834
{
1835
// atan2: 0 at 3 o'clock, CCW. Convert to clockwise from top.
1836
var a = ang + Math.PI / 2;
1837
if (a < 0) { a += 2 * Math.PI; }
1838
var mins = Math.round((a / (2 * Math.PI)) * 1440 / 5) * 5;
1839
if (mins >= 1440) { mins = 0; }
1840
if (mins < 0) { mins = 0; }
1841
return mins;
1842
};
1843
1844
CeasefireClock.arcPath = function (r, startMin, endMin)
1845
{
1846
var cx = this.cx, cy = this.cy;
1847
var a1 = this.minsToAngle(startMin);
1848
var a2 = this.minsToAngle(endMin);
1849
var x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1);
1850
var x2 = cx + r * Math.cos(a2), y2 = cy + r * Math.sin(a2);
1851
var delta = endMin - startMin;
1852
if (delta <= 0) { delta += 1440; }
1853
var large = delta > 720 ? 1 : 0;
1854
return 'M ' + cx + ' ' + cy + ' L ' + x1 + ' ' + y1 + ' A ' + r + ' ' + r + ' 0 ' + large + ' 1 ' + x2 + ' ' + y2 + ' Z';
1855
};
1856
1857
CeasefireClock.handlePos = function (mins)
1858
{
1859
var a = this.minsToAngle(mins);
1860
return { x: this.cx + this.r * Math.cos(a), y: this.cy + this.r * Math.sin(a) };
1861
};
1862
1863
CeasefireClock.render = function (container, ranges, opts)
1864
{
1865
opts = opts || {};
1866
var self = this;
1867
ranges = Rules.normalizeRanges(ranges || []);
1868
var size = this.size;
1869
var svgNS = 'http://www.w3.org/2000/svg';
1870
container.innerHTML = '';
1871
var svg = document.createElementNS(svgNS, 'svg');
1872
svg.setAttribute('viewBox', '0 0 ' + size + ' ' + size);
1873
svg.setAttribute('width', String(size));
1874
svg.setAttribute('height', String(size));
1875
svg.setAttribute('role', 'img');
1876
1877
function el(name, attrs)
1878
{
1879
var n = document.createElementNS(svgNS, name);
1880
Object.keys(attrs).forEach(function (k) { n.setAttribute(k, attrs[k]); });
1881
return n;
1882
}
1883
1884
// Allowed (gold) background disc
1885
svg.appendChild(el('circle', {
1886
cx: this.cx, cy: this.cy, r: this.r,
1887
fill: '#3a3420', stroke: '#e8c547', 'stroke-width': '3'
1888
}));
1889
1890
// Cease-fire slices (red)
1891
ranges.forEach(function (r, i)
1892
{
1893
var s = Rules.hmToMinutes(r.start);
1894
var e = Rules.hmToMinutes(r.end);
1895
var slices = e > s ? [[s, e]] : [[s, 1440], [0, e]];
1896
slices.forEach(function (sl)
1897
{
1898
if (sl[1] === sl[0]) { return; }
1899
svg.appendChild(el('path', {
1900
d: self.arcPath(self.r - 1, sl[0], sl[1]),
1901
fill: '#8a2a2a',
1902
'fill-opacity': '0.92',
1903
'data-range': String(i)
1904
}));
1905
});
1906
});
1907
1908
// Ticks and labels (0 at top, then 3, 6, 12, 18…)
1909
for (var h = 0; h < 24; h++)
1910
{
1911
var mins = h * 60;
1912
var a = this.minsToAngle(mins);
1913
var inner = this.r - (h % 3 === 0 ? 14 : 7);
1914
var outer = this.r;
1915
svg.appendChild(el('line', {
1916
x1: this.cx + inner * Math.cos(a),
1917
y1: this.cy + inner * Math.sin(a),
1918
x2: this.cx + outer * Math.cos(a),
1919
y2: this.cy + outer * Math.sin(a),
1920
stroke: '#e8eaf2',
1921
'stroke-width': h % 6 === 0 ? '2.2' : '1',
1922
'stroke-opacity': '0.7'
1923
}));
1924
if (h % 3 === 0)
1925
{
1926
var tx = this.cx + (this.r + 22) * Math.cos(a);
1927
var ty = this.cy + (this.r + 22) * Math.sin(a);
1928
var lab = el('text', {
1929
x: tx, y: ty,
1930
fill: '#e8c547',
1931
'font-size': '13',
1932
'font-weight': '700',
1933
'text-anchor': 'middle',
1934
'dominant-baseline': 'middle',
1935
'pointer-events': 'none'
1936
});
1937
lab.textContent = String(h);
1938
svg.appendChild(lab);
1939
}
1940
}
1941
1942
// Inner hole so it looks like a ring-pie (keep a smaller gold disc for “now” later)
1943
svg.appendChild(el('circle', {
1944
cx: this.cx, cy: this.cy, r: 36,
1945
fill: '#0c1020', stroke: '#e8c54755', 'stroke-width': '1.5'
1946
}));
1947
var mid = el('text', {
1948
x: this.cx, y: this.cy + 1,
1949
fill: '#e8eaf2',
1950
'font-size': '11',
1951
'text-anchor': 'middle',
1952
'dominant-baseline': 'middle',
1953
'pointer-events': 'none'
1954
});
1955
mid.textContent = '24h';
1956
svg.appendChild(mid);
1957
1958
// Handles
1959
if (opts.editable)
1960
{
1961
ranges.forEach(function (r, i)
1962
{
1963
['start', 'end'].forEach(function (which)
1964
{
1965
var pos = self.handlePos(Rules.hmToMinutes(r[which]));
1966
var c = el('circle', {
1967
cx: pos.x, cy: pos.y, r: 14,
1968
fill: '#e8c547',
1969
stroke: '#1a1404',
1970
'stroke-width': '2',
1971
'data-range': String(i),
1972
'data-which': which,
1973
style: 'cursor:grab; touch-action:none'
1974
});
1975
// invisible larger hit target
1976
var hit = el('circle', {
1977
cx: pos.x, cy: pos.y, r: 22,
1978
fill: 'transparent',
1979
'data-range': String(i),
1980
'data-which': which,
1981
style: 'cursor:grab; touch-action:none'
1982
});
1983
svg.appendChild(hit);
1984
svg.appendChild(c);
1985
});
1986
});
1987
}
1988
1989
container.appendChild(svg);
1990
if (!opts.editable) { return; }
1991
1992
var drag = null;
1993
var painting = null;
1994
1995
function localMins(ev)
1996
{
1997
var rect = svg.getBoundingClientRect();
1998
var cx = ev.clientX != null ? ev.clientX : ev.touches[0].clientX;
1999
var cy = ev.clientY != null ? ev.clientY : ev.touches[0].clientY;
2000
var x = (cx - rect.left) / rect.width * size;
2001
var y = (cy - rect.top) / rect.height * size;
2002
return self.angleToMins(Math.atan2(y - self.cy, x - self.cx));
2003
}
2004
2005
function commit(next)
2006
{
2007
if (opts.onChange) { opts.onChange(next); }
2008
}
2009
2010
svg.addEventListener('pointerdown', function (e)
2011
{
2012
e.preventDefault();
2013
svg.setPointerCapture(e.pointerId);
2014
var t = e.target;
2015
var ri = t.getAttribute && t.getAttribute('data-range');
2016
var which = t.getAttribute && t.getAttribute('data-which');
2017
if (ri != null && which)
2018
{
2019
drag = { i: parseInt(ri, 10), which: which };
2020
return;
2021
}
2022
// Start a new range from this angle, drag to set the end.
2023
var m = localMins(e);
2024
painting = { start: m, end: (m + 60) % 1440 };
2025
});
2026
svg.addEventListener('pointermove', function (e)
2027
{
2028
if (!drag && !painting) { return; }
2029
e.preventDefault();
2030
var m = localMins(e);
2031
if (drag)
2032
{
2033
var next = ranges.map(function (r) { return { start: r.start, end: r.end }; });
2034
if (!next[drag.i]) { return; }
2035
next[drag.i][drag.which] = Rules.minutesToHm(m);
2036
// Live preview
2037
self.render(container, next, opts);
2038
// re-bind happens via render → we need to keep dragging. Store on object.
2039
CeasefireClock._pending = { drag: drag, ranges: next, opts: opts, container: container };
2040
}
2041
else if (painting)
2042
{
2043
painting.end = m;
2044
var preview = ranges.concat([{
2045
start: Rules.minutesToHm(painting.start),
2046
end: Rules.minutesToHm(painting.end === painting.start ? (painting.start + 5) % 1440 : painting.end)
2047
}]);
2048
self.render(container, preview, opts);
2049
CeasefireClock._pending = { painting: painting, ranges: ranges, opts: opts, container: container };
2050
}
2051
});
2052
function endDrag(e)
2053
{
2054
var pending = CeasefireClock._pending;
2055
CeasefireClock._pending = null;
2056
if (drag && pending && pending.ranges)
2057
{
2058
var d = drag;
2059
drag = null;
2060
commit(pending.ranges);
2061
return;
2062
}
2063
if (painting)
2064
{
2065
var p = painting;
2066
painting = null;
2067
if (p.start === p.end) { self.render(container, ranges, opts); return; }
2068
commit(ranges.concat([{
2069
start: Rules.minutesToHm(p.start),
2070
end: Rules.minutesToHm(p.end)
2071
}]));
2072
}
2073
drag = null;
2074
}
2075
svg.addEventListener('pointerup', endDrag);
2076
svg.addEventListener('pointercancel', endDrag);
2077
};
2078
2079
// Re-attach pointer handlers after a live-preview re-render by using
2080
// event delegation on the container (already on svg after each render).
2081
// The _pending flag lets pointermove after re-render continue: we also
2082
// bind at the document level during a drag.
2083
(function ()
2084
{
2085
var active = false;
2086
document.addEventListener('pointermove', function (e)
2087
{
2088
var p = CeasefireClock._pending;
2089
if (!p || !p.opts) { return; }
2090
if (!p.drag && !p.painting) { return; }
2091
// The new svg already has handlers; this is a safety net no-op if they fire.
2092
});
2093
})();
2094
2095
/* boot */
2096
if (typeof document !== 'undefined')
2097
{
2098
if (document.readyState === 'loading')
2099
{ document.addEventListener('DOMContentLoaded', function () { App.init(); }); }
2100
else
2101
{ App.init(); }
2102
}
2103
2104
if (typeof module !== 'undefined' && module.exports)
2105
{ module.exports = { App: App, CeasefireClock: CeasefireClock, Rules: (typeof Rules !== 'undefined' ? Rules : null) }; }
@@ -0,0 +1,2105 @@1
'use strict';2
3
var App = {4
screen: 'menu',5
games: [],6
game: null,7
selected: null, // player id or 'self-move'8
pollTimer: null,9
tickTimer: null,10
replay: null, // { events, index, timer, snapshot }11
rulesDirty: false,12
savingRules: false13
};14
15
function $(id)16
{17
return document.getElementById(id);18
}19
20
function showScreen(name)21
{22
['menu', 'lobby', 'game'].forEach(function (s)23
{24
var el = $(s);25
if (el) { el.hidden = s !== name; }26
});27
App.screen = name;28
$('top-bar').hidden = name !== 'game';29
if (name !== 'game')30
{ App.stopReplay(); }31
}32
33
function showError(id, err)34
{35
var el = $(id);36
if (!el) { return; }37
if (!err)38
{39
el.hidden = true;40
el.textContent = '';41
return;42
}43
var msg = err && (err.code || err.message) ? I18n.error(err.code || err.message) : String(err);44
if (err && err.status)45
{ msg = I18n.t('error.serverStatus', { status: err.status }); }46
el.textContent = msg;47
el.hidden = false;48
}49
50
function initials(name)51
{52
if (!name) { return '?'; }53
var parts = String(name).trim().split(/\s+/);54
var s = parts[0].charAt(0);55
if (parts.length > 1)56
{ s += parts[parts.length - 1].charAt(0); }57
return s.toUpperCase();58
}59
60
function avatarNode(player, size, fixed)61
{62
size = size || 40;63
var wrap = document.createElement('span');64
wrap.className = 'avatar-wrap';65
wrap.style.setProperty('--c', player.color || '#fff');66
wrap.style.setProperty('--sz', size + 'px');67
if (fixed)68
{69
wrap.classList.add('avatar-wrap-fixed');70
wrap.style.width = size + 'px';71
wrap.style.height = size + 'px';72
}73
function stylePiece(el)74
{75
el.className = (el.className ? el.className + ' ' : '') + 'piece' + (player.alive === false ? ' dead' : '');76
if (fixed)77
{78
el.classList.add('piece-fixed');79
el.style.width = size + 'px';80
el.style.height = size + 'px';81
el.style.borderColor = player.color || '#fff';82
}83
else84
{85
el.style.borderColor = player.color || '#fff';86
}87
}88
if (player.avatar)89
{90
var img = document.createElement('img');91
img.alt = player.name || '';92
img.width = size;93
img.height = size;94
stylePiece(img);95
img.src = player.avatar;96
img.addEventListener('error', function ()97
{98
img.remove();99
var fb = document.createElement('span');100
fb.className = 'piece-initials';101
stylePiece(fb);102
fb.textContent = initials(player.name);103
wrap.appendChild(fb);104
});105
wrap.appendChild(img);106
}107
else108
{109
var fb = document.createElement('span');110
fb.className = 'piece-initials';111
stylePiece(fb);112
fb.textContent = initials(player.name);113
wrap.appendChild(fb);114
}115
return wrap;116
}117
118
function findPlayer(id)119
{120
if (!App.game || !App.game.players) { return null; }121
for (var i = 0; i < App.game.players.length; i++)122
{123
if (App.game.players[i].id === id)124
{ return App.game.players[i]; }125
}126
return null;127
}128
129
function you()130
{131
return App.game ? findPlayer(App.game.you) : null;132
}133
134
/* ---------- init ---------- */135
136
App.init = function ()137
{138
I18n.init();139
I18n.bindPicker();140
I18n.onChange(function ()141
{142
App.render();143
});144
this.bind();145
this.localLinks();146
var params = new URLSearchParams(location.search);147
var join = params.get('join');148
Api.loadMe().then(function (data)149
{150
if (data.locale)151
{ I18n.applyFromProfile(data.locale); }152
App.games = data.games || [];153
App.renderMenu(data);154
if (join)155
{156
if (!Api.me)157
{158
location.href = 'auth.php?next=' + encodeURIComponent('index.html?join=' + join);159
return;160
}161
App.doJoin(join);162
}163
}).catch(function (err)164
{165
showError('menu-error', err);166
App.renderMenu({});167
});168
this.tickTimer = setInterval(function () { App.tickClocks(); }, 250);169
document.addEventListener('visibilitychange', function ()170
{171
if (document.hidden)172
{173
App.stopPoll();174
}175
else if (App.game && App.screen !== 'menu')176
{177
App.refreshFull();178
App.startPoll();179
}180
});181
};182
183
App.localLinks = function ()184
{185
var span = $('local-links');186
if (!span) { return; }187
span.innerHTML = '';188
for (var i = 1; i <= 8; i++)189
{190
if (i > 1) { span.appendChild(document.createTextNode(' · ')); }191
var a = document.createElement('a');192
a.href = 'auth.php?test=' + i;193
a.textContent = 'test_user_' + i;194
span.appendChild(a);195
}196
};197
198
App.bind = function ()199
{200
$('btn-create').addEventListener('click', function () { App.createLobby(); });201
$('join-form').addEventListener('submit', function (e)202
{203
e.preventDefault();204
App.doJoin($('join-code').value);205
});206
$('lobby-back').addEventListener('click', function () { App.toMenu(); });207
$('btn-copy').addEventListener('click', function () { App.copyInvite(); });208
$('btn-start').addEventListener('click', function () { App.startGame(); });209
$('btn-leave').addEventListener('click', function () { App.leaveLobby(); });210
$('btn-upgrade').addEventListener('click', function () { App.act({ type: 'upgrade' }); });211
$('btn-settings').addEventListener('click', function () { $('settings-panel').hidden = false; });212
$('settings-close').addEventListener('click', function () { $('settings-panel').hidden = true; });213
$('btn-to-menu').addEventListener('click', function ()214
{215
$('settings-panel').hidden = true;216
App.toMenu();217
});218
$('btn-surrender').addEventListener('click', function () { App.confirmSurrender(); });219
$('modal-close').addEventListener('click', function () { App.closeModal(); });220
$('modal').addEventListener('click', function (e)221
{222
if (e.target === $('modal')) { App.closeModal(); }223
});224
$('sheet-close').addEventListener('click', function () { App.closeSheet(); });225
$('sheet').addEventListener('click', function (e)226
{227
if (e.target === $('sheet')) { App.closeSheet(); }228
});229
$('tl-play').addEventListener('click', function () { App.toggleReplay(); });230
$('tl-live').addEventListener('click', function () { App.jumpToPresent(); });231
if ($('tl-back')) { $('tl-back').addEventListener('click', function () { App.stepReplay(-1); }); }232
if ($('tl-fwd')) { $('tl-fwd').addEventListener('click', function () { App.stepReplay(1); }); }233
this.bindTimelineScrub();234
this.bindRuleEditors();235
document.addEventListener('keydown', function (e)236
{237
if (e.key === 'Escape')238
{239
App.closeModal();240
App.closeSheet();241
$('settings-panel').hidden = true;242
return;243
}244
App.onGameKey(e);245
});246
};247
248
App.onGameKey = function (e)249
{250
if (App.screen !== 'game' || !App.game) { return; }251
var t = e.target;252
var tag = (t && t.tagName) ? t.tagName.toUpperCase() : '';253
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable))254
{ return; }255
if (e.altKey || e.ctrlKey || e.metaKey) { return; }256
if (e.key === 'ArrowLeft')257
{258
e.preventDefault();259
App.stepReplay(-1);260
}261
else if (e.key === 'ArrowRight')262
{263
e.preventDefault();264
App.stepReplay(1);265
}266
else if (e.key === ' ' || e.key === 'Spacebar' || e.code === 'Space')267
{268
e.preventDefault();269
App.toggleReplay();270
}271
else if (e.key === 'End')272
{273
e.preventDefault();274
App.jumpToPresent();275
}276
};277
278
App.jumpToPresent = function ()279
{280
App.stopReplay();281
if (App.game) { App.renderGame(); }282
};283
284
App.stepReplay = function (dir)285
{286
if (!App.game || App.game.status === 'lobby') { return; }287
var n = this.spendEvents(App.game).length;288
if (!n && dir) { return; }289
var idx = App.replay ? App.replay.index : n;290
var next = Math.max(0, Math.min(n, idx + dir));291
if (App.replay && App.replay.timer)292
{293
clearInterval(App.replay.timer);294
App.replay.timer = null;295
}296
if (next >= n)297
{298
this.jumpToPresent();299
return;300
}301
this.jumpReplay(next, { animate: dir > 0 });302
};303
304
305
App.bindRuleEditors = function ()306
{307
['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'rule-ap-loot', 'rule-ap-time'].forEach(function (id)308
{309
if ($(id)) { $(id).addEventListener('change', function () { App.onRulesChange(); }); }310
});311
$('cf-add').addEventListener('click', function ()312
{313
var ranges = App.currentCfRanges();314
ranges.push({ start: '22:00', end: '06:00' });315
App.setCfRanges(ranges);316
App.onRulesChange();317
});318
var vis = $('lobby-visibility');319
if (vis)320
{321
vis.addEventListener('change', function () { App.onRulesChange(); });322
}323
};324
325
App.visKeys = ['vis_shots', 'vis_gifts', 'vis_ap', 'vis_range', 'vis_lives'];326
327
App.syncVisRadios = function (r, isHost)328
{329
App.visKeys.forEach(function (k)330
{331
var val = (r && r[k]) || 'public';332
document.querySelectorAll('input[name="' + k + '"]').forEach(function (inp)333
{334
inp.checked = inp.value === val;335
inp.disabled = !isHost;336
});337
});338
};339
340
App.readVisRules = function ()341
{342
var o = {};343
App.visKeys.forEach(function (k)344
{345
var inp = document.querySelector('input[name="' + k + '"]:checked');346
o[k] = inp ? inp.value : 'public';347
});348
return o;349
};350
351
App.render = function ()352
{353
I18n.apply();354
I18n.renderPicker();355
if (App.screen === 'menu') { App.renderMenu({ games: App.games, me: Api.me, configured: Api.configured, local: Api.local }); }356
else if (App.screen === 'lobby') { App.renderLobby(); }357
else if (App.screen === 'game') { App.renderGame(); }358
};359
360
/* ---------- menu ---------- */361
362
App.renderMenu = function (data)363
{364
showScreen('menu');365
App.stopPoll();366
data = data || {};367
var me = data.me !== undefined ? data.me : Api.me;368
$('menu-guest').hidden = !!me;369
$('menu-user').hidden = !me;370
$('menu-guest-hint').hidden = !!me;371
$('menu-actions').hidden = !me;372
$('my-games').hidden = !me;373
$('menu-unconfigured').hidden = !!Api.configured || !!Api.local;374
$('menu-local-login').hidden = !Api.local;375
if (me)376
{377
$('menu-name').textContent = me.name;378
var av = $('menu-avatar');379
if (me.avatar) { av.src = me.avatar; av.hidden = false; }380
else { av.hidden = true; }381
}382
App.games = data.games || App.games || [];383
var list = $('games-list');384
list.innerHTML = '';385
$('no-games').hidden = App.games.length > 0;386
App.games.forEach(function (g)387
{388
var li = document.createElement('li');389
var info = document.createElement('div');390
info.style.flex = '1';391
var st = g.status === 'lobby' ? I18n.t('menu.statusLobby')392
: g.status === 'finished' ? I18n.t('menu.statusFinished')393
: I18n.t('menu.statusRunning');394
var sub = I18n.plural('lobby.playerCount', g.players);395
if (g.status === 'finished')396
{397
if (g.draw) { sub = I18n.t('menu.draw'); }398
else if (g.you_won) { sub = I18n.t('menu.youWon'); }399
else400
{401
var w = (g.names || []).filter(function (p) { return p.id === g.winner_id; })[0];402
sub = I18n.t('menu.winnerIs', { name: w ? w.name : '?' });403
}404
}405
info.innerHTML = '<strong>' + st + '</strong> · <span class="mono">' + escapeHtml(g.code) + '</span><br><span class="hint">' + escapeHtml(sub) + '</span>';406
var btn = document.createElement('button');407
btn.type = 'button';408
btn.textContent = I18n.t(g.status === 'finished' ? 'menu.open' : 'menu.continue');409
btn.addEventListener('click', function () { App.openGame(g.id, g.status); });410
li.appendChild(info);411
li.appendChild(btn);412
list.appendChild(li);413
});414
I18n.apply($('menu'));415
};416
417
App.toMenu = function ()418
{419
App.game = null;420
App.selected = null;421
App.stopPoll();422
Api.games().then(function (data)423
{424
App.games = data.games || [];425
App.renderMenu(data);426
}).catch(function () { App.renderMenu({}); });427
// clean join from URL428
if (location.search)429
{ history.replaceState({}, '', 'index.html'); }430
};431
432
App.createLobby = function ()433
{434
showError('menu-error');435
Api.createLobby(Rules.defaultRules()).then(function (data)436
{437
App.enter(data.game);438
}).catch(function (err) { showError('menu-error', err); });439
};440
441
App.doJoin = function (code)442
{443
showError('menu-error');444
code = String(code || '').trim();445
if (!code) { return; }446
Api.join(code).then(function (data)447
{448
App.enter(data.game);449
}).catch(function (err)450
{451
// Already a member of a game that has started: open it from the list.452
if (err && err.code === 'game_started')453
{454
var want = String(code).toUpperCase();455
var existing = (App.games || []).filter(function (g)456
{457
return String(g.code || '').toUpperCase() === want;458
})[0];459
if (existing)460
{461
App.openGame(existing.id, existing.status);462
return;463
}464
}465
showError('menu-error', err);466
});467
};468
469
App.openGame = function (id, status)470
{471
Api.game(id).then(function (data)472
{473
App.enter(data.game);474
}).catch(function (err) { showError('menu-error', err); });475
};476
477
App.enter = function (game)478
{479
App.game = game;480
if (game.status === 'lobby')481
{482
showScreen('lobby');483
App.renderLobby();484
}485
else486
{487
showScreen('game');488
App.renderGame();489
}490
App.startPoll();491
if (game && game.code)492
{493
history.replaceState({}, '', 'index.html?join=' + encodeURIComponent(game.code));494
}495
};496
497
/* ---------- lobby ---------- */498
499
App.renderLobby = function ()500
{501
var g = App.game;502
if (!g) { return; }503
$('lobby-code').textContent = g.code;504
var url = location.origin + location.pathname.replace(/index\.html$/, '') + 'index.html?join=' + encodeURIComponent(g.code);505
$('invite-link').value = url;506
var isHost = g.host_id === g.you;507
var list = $('lobby-players');508
list.innerHTML = '';509
(g.players || []).forEach(function (p)510
{511
var li = document.createElement('li');512
li.appendChild(avatarNode(p, 40, true));513
var name = document.createElement('span');514
name.style.flex = '1';515
name.textContent = p.name + (p.is_you ? ' (' + I18n.t('lobby.you') + ')' : '') + (p.is_host ? ' · ' + I18n.t('lobby.host') : '');516
li.appendChild(name);517
var dot = document.createElement('span');518
dot.className = 'player-dot';519
dot.style.background = p.color;520
li.appendChild(dot);521
list.appendChild(li);522
});523
var n = (g.players || []).length;524
$('lobby-need').hidden = n >= 2;525
$('btn-start').hidden = !isHost;526
$('btn-start').disabled = n < 2;527
$('lobby-waiting').hidden = isHost;528
// Rules529
var r = g.rules || Rules.defaultRules();530
$('rule-jury').checked = !!r.jury;531
if ($('rule-ap-loot')) { $('rule-ap-loot').checked = !!r.ap_loot; }532
if ($('rule-ap-time')) { $('rule-ap-time').value = r.ap_time || '00:00'; }533
$('rule-shrink').checked = !!r.shrinking_arena;534
$('rule-shrink-days').value = r.shrink_interval_days || 7;535
$('rule-ceasefire').checked = !!r.ceasefire;536
$('shrink-days-wrap').hidden = !r.shrinking_arena;537
$('ceasefire-editor').hidden = !r.ceasefire;538
['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'cf-add', 'rule-ap-loot', 'rule-ap-time'].forEach(function (id)539
{540
if ($(id)) { $(id).disabled = !isHost; }541
});542
App.renderCfEditor(r.ceasefire_ranges || [], isHost);543
App.syncVisRadios(r, isHost);544
I18n.apply($('lobby'));545
};546
547
App.currentCfRanges = function ()548
{549
return (App.game && App.game.rules && App.game.rules.ceasefire_ranges) || [];550
};551
552
App.setCfRanges = function (ranges)553
{554
if (!App.game.rules) { App.game.rules = Rules.defaultRules(); }555
App.game.rules.ceasefire_ranges = Rules.normalizeRanges(ranges);556
App.renderCfEditor(App.game.rules.ceasefire_ranges, App.game.host_id === App.game.you);557
};558
559
App.renderCfEditor = function (ranges, editable)560
{561
CeasefireClock.render($('cf-clock'), ranges, {562
editable: editable,563
onChange: function (next)564
{565
App.setCfRanges(next);566
App.onRulesChange();567
}568
});569
var ul = $('cf-ranges');570
ul.innerHTML = '';571
if (!ranges.length)572
{573
var empty = document.createElement('li');574
empty.className = 'hint';575
empty.setAttribute('data-i18n', 'lobby.ceasefireEmpty');576
empty.textContent = I18n.t('lobby.ceasefireEmpty');577
ul.appendChild(empty);578
return;579
}580
ranges.forEach(function (r, i)581
{582
var li = document.createElement('li');583
var a = document.createElement('input');584
a.type = 'time';585
a.value = r.start;586
a.setAttribute('aria-label', I18n.t('lobby.ceasefireStart'));587
a.disabled = !editable;588
var b = document.createElement('input');589
b.type = 'time';590
b.value = r.end;591
b.setAttribute('aria-label', I18n.t('lobby.ceasefireEnd'));592
b.disabled = !editable;593
function commit()594
{595
var next = App.currentCfRanges().slice();596
next[i] = { start: a.value, end: b.value };597
App.setCfRanges(next);598
App.onRulesChange();599
}600
a.addEventListener('change', commit);601
b.addEventListener('change', commit);602
var rm = document.createElement('button');603
rm.type = 'button';604
rm.className = 'btn-secondary';605
rm.textContent = I18n.t('lobby.ceasefireRemove');606
rm.disabled = !editable;607
rm.addEventListener('click', function ()608
{609
var next = App.currentCfRanges().slice();610
next.splice(i, 1);611
App.setCfRanges(next);612
App.onRulesChange();613
});614
li.appendChild(a);615
li.appendChild(document.createTextNode('–'));616
li.appendChild(b);617
li.appendChild(rm);618
ul.appendChild(li);619
});620
};621
622
App.onRulesChange = function ()623
{624
if (!App.game || App.game.status !== 'lobby') { return; }625
if (App.game.host_id !== App.game.you) { return; }626
$('shrink-days-wrap').hidden = !$('rule-shrink').checked;627
$('ceasefire-editor').hidden = !$('rule-ceasefire').checked;628
var rules = {629
jury: $('rule-jury').checked,630
shrinking_arena: $('rule-shrink').checked,631
shrink_interval_days: parseInt($('rule-shrink-days').value, 10) || 7,632
ceasefire: $('rule-ceasefire').checked,633
ceasefire_ranges: App.currentCfRanges(),634
ap_loot: $('rule-ap-loot') ? $('rule-ap-loot').checked : false,635
ap_time: ($('rule-ap-time') && $('rule-ap-time').value) ? $('rule-ap-time').value : '00:00'636
};637
Object.assign(rules, App.readVisRules());638
App.game.rules = Object.assign({}, App.game.rules, rules);639
App.rulesDirty = true;640
if (App._rulesTimer) { clearTimeout(App._rulesTimer); }641
App._rulesTimer = setTimeout(function ()642
{643
if (!App.rulesDirty) { return; }644
App.rulesDirty = false;645
Api.setRules(App.game.id, App.game.rules).then(function (data)646
{647
App.game = data.game;648
App.renderLobby();649
}).catch(function (err) { showError('lobby-error', err); });650
}, 350);651
};652
653
App.copyInvite = function ()654
{655
var v = $('invite-link').value;656
function ok()657
{658
$('copy-status').hidden = false;659
setTimeout(function () { $('copy-status').hidden = true; }, 1500);660
}661
if (navigator.clipboard && navigator.clipboard.writeText)662
{663
navigator.clipboard.writeText(v).then(ok).catch(function ()664
{665
$('invite-link').select();666
try { document.execCommand('copy'); ok(); } catch (e) {}667
});668
}669
else670
{671
$('invite-link').select();672
try { document.execCommand('copy'); ok(); } catch (e) {}673
}674
};675
676
App.startGame = function ()677
{678
showError('lobby-error');679
Api.start(App.game.id).then(function (data)680
{681
App.enter(data.game);682
}).catch(function (err) { showError('lobby-error', err); });683
};684
685
App.leaveLobby = function ()686
{687
Api.leave(App.game.id).then(function () { App.toMenu(); })688
.catch(function (err) { showError('lobby-error', err); });689
};690
691
/* ---------- game ---------- */692
693
App.renderGame = function ()694
{695
var g = App.replay ? App.replay.view : App.game;696
if (!g) { return; }697
this.renderHud(g);698
this.renderBoard(g);699
this.renderJury(g);700
this.renderTimeline(App.game); // ticks from the (already filtered) event list701
this.tickClocks();702
I18n.apply($('game'));703
I18n.apply($('top-bar'));704
if (!App.replay) { this.clearBoardFx(); }705
};706
707
App.renderHud = function (g)708
{709
var me = findIn(g.players, g.you) || you();710
var stats = $('you-stats');711
if (me)712
{713
stats.innerHTML = '<strong>' + escapeHtml(me.name) + '</strong> · '714
+ I18n.t('game.lives') + ' <strong>' + me.lives + '</strong> · '715
+ I18n.t('game.ap') + ' <strong>' + me.ap + '</strong> · '716
+ I18n.t('game.range') + ' <strong>' + me.range + '</strong>';717
}718
var legal = g.legal || {};719
$('btn-upgrade').hidden = !legal.upgrade;720
$('btn-upgrade').disabled = !legal.upgrade;721
$('day-label').textContent = I18n.t('game.day', { n: g.day || 0 });722
var sb = $('shrink-banner');723
if (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null)724
{725
sb.hidden = false;726
if (g.shrink_in_days === 0) { sb.textContent = I18n.t('game.shrinkToday'); }727
else if (g.shrink_in_days === 1) { sb.textContent = I18n.t('game.shrinkTomorrow'); }728
else { sb.textContent = I18n.plural('game.shrinkInDays', g.shrink_in_days); }729
}730
else { sb.hidden = true; }731
var banner = $('game-banner');732
if (g.status === 'finished')733
{734
banner.hidden = false;735
if (g.draw) { banner.textContent = I18n.t('game.draw'); }736
else if (g.winner_id === g.you) { banner.textContent = I18n.t('game.youWin'); }737
else738
{739
var w = findIn(g.players, g.winner_id);740
banner.textContent = I18n.t('game.winner', { name: w ? w.name : '?' });741
}742
}743
else if (me && !me.alive)744
{745
banner.hidden = false;746
banner.textContent = I18n.t('game.spectating');747
}748
else { banner.hidden = true; }749
};750
751
function findIn(list, id)752
{753
if (!list) { return null; }754
for (var i = 0; i < list.length; i++)755
{756
if (list[i].id === id) { return list[i]; }757
}758
return null;759
}760
761
App.renderBoard = function (g)762
{763
var board = $('board');764
var size = g.grid || 6;765
var inset = g.arena_inset || 0;766
var nextInset = (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null && g.max_inset > inset)767
? inset + 1 : null;768
board.style.setProperty('--n', String(size));769
board.style.gridTemplateColumns = 'repeat(' + size + ', 1fr)';770
board.style.gridTemplateRows = 'repeat(' + size + ', 1fr)';771
board.innerHTML = '';772
var legal = (!App.replay && g.legal) ? g.legal : { move: [], shoot: [] };773
var moveSet = {};774
(legal.move || []).forEach(function (t) { moveSet[t.x + ',' + t.y] = true; });775
var me = findIn(g.players, g.you);776
var showMoves = App.selected && me && App.selected === me.id;777
for (var y = 0; y < size; y++)778
{779
for (var x = 0; x < size; x++)780
{781
var cell = document.createElement('button');782
cell.type = 'button';783
cell.className = 'cell';784
cell.setAttribute('role', 'gridcell');785
cell.dataset.x = String(x);786
cell.dataset.y = String(y);787
var passable = Rules.isPassable(size, inset, x, y);788
if (!passable)789
{790
cell.classList.add('impassable');791
cell.disabled = true;792
cell.title = I18n.t('game.impassable');793
}794
else if (nextInset != null && !Rules.isPassable(size, nextInset, x, y))795
{796
cell.classList.add('threat');797
cell.title = I18n.t('game.willShrink');798
}799
if (showMoves && moveSet[x + ',' + y])800
{ cell.classList.add('move-target'); }801
var occupant = null;802
(g.players || []).forEach(function (p)803
{804
if (p.x === x && p.y === y) { occupant = p; }805
});806
// Prefer living occupant if two (dead + living shouldn't share, but dead stay visually)807
(g.players || []).forEach(function (p)808
{809
if (p.x === x && p.y === y && p.alive) { occupant = p; }810
});811
if (occupant)812
{813
var node = avatarNode(occupant, 48);814
var pic = node.firstChild;815
if (pic) { cell.appendChild(pic); }816
if (App.selected === occupant.id) { cell.classList.add('selected'); }817
if (!App.replay && legal.shoot && legal.shoot.indexOf(occupant.id) >= 0)818
{ cell.classList.add('in-range'); }819
}820
(function (cx, cy, occ)821
{822
cell.addEventListener('click', function () { App.onCell(cx, cy, occ); });823
})(x, y, occupant);824
board.appendChild(cell);825
}826
}827
};828
829
App.onCell = function (x, y, occupant)830
{831
if (App.replay) { this.stopReplay(); }832
var g = App.game;833
if (!g || g.status !== 'running')834
{835
if (occupant) { this.openInfo(occupant); }836
return;837
}838
var me = you();839
var legal = g.legal || {};840
// Move onto highlighted tile841
if (me && App.selected === me.id && !occupant)842
{843
var ok = (legal.move || []).some(function (t) { return t.x === x && t.y === y; });844
if (ok)845
{846
this.act({ type: 'move', x: x, y: y });847
App.selected = null;848
return;849
}850
}851
if (occupant)852
{853
if (occupant.is_you || occupant.id === g.you)854
{855
App.selected = occupant.id;856
this.renderGame();857
return;858
}859
this.openPlayerOptions(occupant);860
return;861
}862
App.selected = null;863
this.renderGame();864
};865
866
App.openPlayerOptions = function (p)867
{868
App.selected = p.id;869
this.renderGame();870
var g = App.game;871
var legal = g.legal || {};872
var body = document.createElement('div');873
body.className = 'opt-list';874
function add(label, fn, disabled, reason)875
{876
var b = document.createElement('button');877
b.type = 'button';878
b.textContent = label;879
if (disabled)880
{881
b.disabled = true;882
if (reason) { b.title = reason; }883
}884
else885
{886
b.addEventListener('click', function () { App.closeSheet(); fn(); });887
}888
body.appendChild(b);889
}890
add(I18n.t('opt.info'), function () { App.openInfo(p); });891
var canAttack = legal.shoot && legal.shoot.indexOf(p.id) >= 0;892
var cfBlock = legal.ceasefire || (g.ceasefire && g.ceasefire.active);893
add(I18n.t('opt.attack'), function () { App.act({ type: 'shoot', target: p.id }); },894
!canAttack,895
cfBlock ? I18n.t('game.attackDisabledReason') : (I18n.t('error.out_of_range')));896
var canGive = legal.give && legal.give.indexOf(p.id) >= 0;897
add(I18n.t('opt.give'), function () { App.openGive(p); }, !canGive);898
add(I18n.t('opt.message'), function () { App.openChat(p); });899
$('sheet-body').innerHTML = '';900
var head = document.createElement('h2');901
head.textContent = p.name;902
$('sheet-body').appendChild(head);903
$('sheet-body').appendChild(body);904
$('sheet').hidden = false;905
};906
907
App.openInfo = function (p)908
{909
var body = document.createElement('div');910
function stat(label, val)911
{912
var shown = (val == null) ? I18n.t('info.hidden') : String(val);913
return '<p>' + label + ': <strong>' + shown + '</strong></p>';914
}915
body.innerHTML = stat(I18n.t('info.lives'), p.lives)916
+ stat(I18n.t('info.ap'), p.ap)917
+ stat(I18n.t('info.range'), p.range);918
if (!p.alive)919
{920
body.innerHTML += '<p>' + I18n.t(p.surrendered ? 'game.surrendered' : 'game.dead') + '</p>';921
}922
var lab = document.createElement('label');923
lab.textContent = I18n.t('info.notes');924
var ta = document.createElement('textarea');925
ta.rows = 5;926
ta.value = p.note || '';927
ta.setAttribute('maxlength', '2000');928
var hint = document.createElement('p');929
hint.className = 'hint';930
hint.textContent = I18n.t('info.notesHint');931
var save = document.createElement('button');932
save.type = 'button';933
save.textContent = I18n.t('info.saveNotes');934
var st = document.createElement('span');935
st.className = 'hint';936
save.addEventListener('click', function ()937
{938
Api.note(App.game.id, p.id, ta.value).then(function (data)939
{940
App.game = data.game;941
st.textContent = I18n.t('info.saved');942
}).catch(function (err) { st.textContent = I18n.error(err.code || err.message); });943
});944
body.appendChild(lab);945
body.appendChild(ta);946
body.appendChild(hint);947
body.appendChild(save);948
body.appendChild(st);949
App.openModal(I18n.t('info.title') + ' — ' + p.name, body);950
};951
952
App.openGive = function (p)953
{954
var me = you();955
var max = me ? me.ap : 1;956
var body = document.createElement('div');957
var lab = document.createElement('label');958
lab.textContent = I18n.t('give.howMany');959
var inp = document.createElement('input');960
inp.type = 'number';961
inp.min = '1';962
inp.max = String(max);963
inp.value = '1';964
inp.inputMode = 'numeric';965
var have = document.createElement('p');966
have.className = 'hint';967
have.textContent = I18n.t('give.youHave', { n: max });968
var btn = document.createElement('button');969
btn.type = 'button';970
btn.textContent = I18n.t('give.send');971
btn.addEventListener('click', function ()972
{973
var n = parseInt(inp.value, 10);974
App.closeModal();975
App.act({ type: 'give', target: p.id, amount: n });976
});977
body.appendChild(lab);978
body.appendChild(inp);979
body.appendChild(have);980
body.appendChild(btn);981
App.openModal(I18n.t('give.title') + ' — ' + p.name, body);982
};983
984
App.openChat = function (p)985
{986
var body = document.createElement('div');987
var log = document.createElement('div');988
log.className = 'chat-log';989
function fill(game)990
{991
log.innerHTML = '';992
var msgs = (game.messages || []).filter(function (m)993
{994
return (m.from === p.id && m.to === game.you) || (m.to === p.id && m.from === game.you);995
});996
if (!msgs.length)997
{998
var em = document.createElement('p');999
em.className = 'hint';1000
em.textContent = I18n.t('chat.empty');1001
log.appendChild(em);1002
}1003
msgs.forEach(function (m)1004
{1005
var b = document.createElement('div');1006
b.className = 'chat-bubble' + (m.from === game.you ? ' mine' : '');1007
b.textContent = m.text;1008
log.appendChild(b);1009
});1010
log.scrollTop = log.scrollHeight;1011
}1012
fill(App.game);1013
var row = document.createElement('form');1014
row.className = 'chat-compose';1015
row.action = '#';1016
var inp = document.createElement('input');1017
inp.type = 'text';1018
inp.maxLength = 1000;1019
inp.placeholder = I18n.t('chat.placeholder');1020
inp.setAttribute('data-i18n-placeholder', 'chat.placeholder');1021
var send = document.createElement('button');1022
send.type = 'submit';1023
send.textContent = I18n.t('chat.send');1024
row.appendChild(inp);1025
row.appendChild(send);1026
row.addEventListener('submit', function (e)1027
{1028
e.preventDefault();1029
var t = inp.value.trim();1030
if (!t) { return; }1031
inp.value = '';1032
Api.message(App.game.id, p.id, t).then(function (data)1033
{1034
App.game = data.game;1035
fill(App.game);1036
}).catch(function (err) { showError('game-error', err); });1037
});1038
body.appendChild(log);1039
body.appendChild(row);1040
App.openModal(I18n.t('chat.title', { name: p.name }), body);1041
// Keep a hook so polls refresh an open chat1042
App._openChat = { id: p.id, fill: fill };1043
inp.focus();1044
};1045
1046
App.openModal = function (title, body)1047
{1048
$('modal-title').textContent = title;1049
$('modal-body').innerHTML = '';1050
$('modal-body').appendChild(body);1051
$('modal').hidden = false;1052
};1053
1054
App.closeModal = function ()1055
{1056
$('modal').hidden = true;1057
App._openChat = null;1058
};1059
1060
App.closeSheet = function ()1061
{1062
$('sheet').hidden = true;1063
};1064
1065
App.renderJury = function (g)1066
{1067
var panel = $('jury-panel');1068
var legal = g.legal || {};1069
if (App.replay || !legal.vote)1070
{1071
panel.hidden = true;1072
return;1073
}1074
panel.hidden = false;1075
var ul = $('jury-list');1076
ul.innerHTML = '';1077
legal.vote.forEach(function (id)1078
{1079
var p = findIn(g.players, id);1080
if (!p) { return; }1081
var li = document.createElement('li');1082
li.appendChild(avatarNode(p, 32, true));1083
var n = document.createElement('span');1084
n.style.flex = '1';1085
n.textContent = p.name;1086
li.appendChild(n);1087
var b = document.createElement('button');1088
b.type = 'button';1089
if (legal.my_vote === id)1090
{1091
b.textContent = I18n.t('jury.votedFor', { name: p.name });1092
b.disabled = true;1093
}1094
else1095
{1096
b.textContent = legal.my_vote ? I18n.t('jury.change') : I18n.t('jury.vote');1097
b.addEventListener('click', function () { App.act({ type: 'vote', target: id }); });1098
}1099
li.appendChild(b);1100
ul.appendChild(li);1101
});1102
};1103
1104
App.confirmSurrender = function ()1105
{1106
$('settings-panel').hidden = true;1107
var body = document.createElement('div');1108
var p = document.createElement('p');1109
p.textContent = I18n.t('game.surrenderConfirm');1110
var yes = document.createElement('button');1111
yes.type = 'button';1112
yes.className = 'btn-danger';1113
yes.textContent = I18n.t('game.surrenderConfirmBtn');1114
yes.addEventListener('click', function ()1115
{1116
App.closeModal();1117
App.act({ type: 'surrender' });1118
});1119
var no = document.createElement('button');1120
no.type = 'button';1121
no.className = 'btn-secondary';1122
no.textContent = I18n.t('game.surrenderCancel');1123
no.addEventListener('click', function () { App.closeModal(); });1124
body.appendChild(p);1125
body.appendChild(yes);1126
body.appendChild(document.createTextNode(' '));1127
body.appendChild(no);1128
App.openModal(I18n.t('game.surrender'), body);1129
};1130
1131
App.act = function (action)1132
{1133
showError('game-error');1134
Api.act(App.game.id, action).then(function (data)1135
{1136
App.game = data.game;1137
App.selected = action.type === 'move' ? null : App.selected;1138
App.renderGame();1139
}).catch(function (err) { showError('game-error', err); });1140
};1141
1142
/* ---------- clocks & polling ---------- */1143
1144
App.tickClocks = function ()1145
{1146
if (App.screen !== 'game' || !App.game) { return; }1147
var now = Api.now();1148
var next = App.game.next_distribution_at;1149
if (next && App.game.status === 'running')1150
{1151
$('ap-hms').textContent = Rules.formatHms(next - now);1152
$('ap-countdown').hidden = false;1153
}1154
else1155
{1156
$('ap-countdown').hidden = App.game.status !== 'running';1157
if (App.game.status !== 'running') { $('ap-hms').textContent = '00:00:00'; }1158
}1159
var cf = App.game.ceasefire;1160
var box = $('cf-countdown');1161
if (cf && cf.enabled && cf.until && App.game.status === 'running')1162
{1163
box.hidden = false;1164
box.classList.toggle('active', !!cf.active);1165
$('cf-label').textContent = I18n.t(cf.active ? 'game.ceasefireLeft' : 'game.ceasefireUntil');1166
$('cf-hms').textContent = Rules.formatHms(cf.until - now);1167
}1168
else { box.hidden = true; }1169
};1170
1171
App.startPoll = function ()1172
{1173
this.stopPoll();1174
this.pollTimer = setInterval(function () { App.poll(); }, 3000);1175
};1176
1177
App.stopPoll = function ()1178
{1179
if (this.pollTimer)1180
{1181
clearInterval(this.pollTimer);1182
this.pollTimer = null;1183
}1184
};1185
1186
App.poll = function ()1187
{1188
if (document.hidden || !App.game) { return; }1189
var id = App.game.id;1190
var v = App.game.version || 0;1191
Api.sync(id, v).then(function (data)1192
{1193
if (!App.game || App.game.id !== id) { return; }1194
if (data.next_distribution_at != null)1195
{ App.game.next_distribution_at = data.next_distribution_at; }1196
if (data.ceasefire !== undefined)1197
{ App.game.ceasefire = data.ceasefire; }1198
if (data.server_now) { /* Api already stored */ }1199
if (data.changed && data.game)1200
{1201
var stayOn = App._openChat && App._openChat.id;1202
App.game = data.game;1203
if (App.screen === 'lobby' && data.game.status === 'lobby')1204
{ App.renderLobby(); }1205
else if (data.game.status !== 'lobby')1206
{1207
if (App.screen !== 'game') { showScreen('game'); }1208
if (!App.replay) { App.renderGame(); }1209
else { App.renderTimeline(App.game); }1210
}1211
if (stayOn && App._openChat)1212
{ App._openChat.fill(App.game); }1213
}1214
App.tickClocks();1215
}).catch(function () { /* transient; next poll retries */ });1216
};1217
1218
App.refreshFull = function ()1219
{1220
if (!App.game) { return; }1221
var id = App.game.id;1222
Api.game(id).then(function (data)1223
{1224
if (!App.game || App.game.id !== id) { return; }1225
App.game = data.game;1226
if (data.game.status === 'lobby') { App.renderLobby(); }1227
else { App.renderGame(); }1228
if (App._openChat) { App._openChat.fill(App.game); }1229
}).catch(function () {});1230
};1231
1232
/* ---------- timeline ---------- */1233
1234
App.spendEvents = function (game)1235
{1236
return (game.events || []).filter(function (e) { return e.spend; });1237
};1238
1239
App.renderTimeline = function (game)1240
{1241
var spends = this.spendEvents(game);1242
var track = $('tl-track');1243
var ticks = $('tl-ticks');1244
ticks.innerHTML = '';1245
var n = spends.length;1246
track.setAttribute('aria-valuemax', String(Math.max(n, 0)));1247
spends.forEach(function (e, i)1248
{1249
var t = document.createElement('div');1250
t.className = 'tl-tick';1251
// Align with playhead: spend i is at index i+1, position (i+1)/n.1252
t.style.left = ((n <= 0 ? 0 : (i + 1) / n) * 100) + '%';1253
ticks.appendChild(t);1254
});1255
var idx = App.replay ? App.replay.index : n;1256
this.setPlayhead(idx, n);1257
$('tl-play').textContent = (App.replay && App.replay.timer) ? '❚❚' : '▶';1258
$('tl-play').title = I18n.t((App.replay && App.replay.timer) ? 'timeline.pause' : 'timeline.play');1259
this.setCaption();1260
track.setAttribute('aria-valuetext', idx + ' / ' + n);1261
};1262
1263
App.setPlayhead = function (idx, n)1264
{1265
var head = $('tl-head');1266
if (n <= 0)1267
{ head.style.left = '0%'; }1268
else if (n === 1)1269
{ head.style.left = (idx <= 0 ? '0%' : '100%'); }1270
else1271
{ head.style.left = (Math.max(0, Math.min(n, idx)) / n) * 100 + '%'; }1272
$('tl-track').setAttribute('aria-valuenow', String(idx));1273
};1274
1275
App.setCaption = function ()1276
{1277
// No direct text log: events are shown only as playback visuals.1278
var el = $('tl-caption');1279
if (el)1280
{1281
el.hidden = true;1282
el.textContent = '';1283
}1284
};1285
1286
App.eventLabel = function (ev, game)1287
{1288
function name(id)1289
{1290
var p = findIn(game.players, id);1291
return p ? p.name : (id || '');1292
}1293
switch (ev.type)1294
{1295
case 'start': return I18n.t('timeline.event.start');1296
case 'move': return I18n.t('timeline.event.move', { name: name(ev.player) });1297
case 'shoot': return I18n.t('timeline.event.shoot', { name: name(ev.player), target: name(ev.target) });1298
case 'give': return I18n.t('timeline.event.give', { name: name(ev.player), target: name(ev.target), n: ev.amount });1299
case 'upgrade': return I18n.t('timeline.event.upgrade', { name: name(ev.player), n: ev.range });1300
case 'surrender': return I18n.t('timeline.event.surrender', { name: name(ev.player) });1301
case 'daily':1302
var s = I18n.t('timeline.event.daily', { n: ev.day });1303
if (ev.jury && ev.jury.winners && ev.jury.winners.length)1304
{1305
var names = ev.jury.winners.map(name);1306
s += ' — ' + (names.length === 11307
? I18n.t('timeline.event.jury', { name: names[0] })1308
: I18n.t('timeline.event.juryTie', { names: names.join(', ') }));1309
}1310
return s;1311
case 'shrink': return I18n.t('timeline.event.shrink');1312
case 'win': return I18n.t('timeline.event.win', { name: name(ev.player) });1313
case 'draw': return I18n.t('timeline.event.draw');1314
case 'death':1315
if (ev.cause === 'shot') { return I18n.t('timeline.event.deathShot', { name: name(ev.player), by: name(ev.by) }); }1316
if (ev.cause === 'shrink') { return I18n.t('timeline.event.deathShrink', { name: name(ev.player) }); }1317
if (ev.cause === 'crushed') { return I18n.t('timeline.event.deathCrushed', { name: name(ev.player) }); }1318
return I18n.t('timeline.event.death', { name: name(ev.player) });1319
default: return ev.type;1320
}1321
};1322
1323
App.bindTimelineScrub = function ()1324
{1325
var track = $('tl-track');1326
var dragging = false;1327
function clientX(ev)1328
{1329
if (ev.clientX != null && ev.clientX !== 0) { return ev.clientX; }1330
if (ev.touches && ev.touches[0]) { return ev.touches[0].clientX; }1331
if (ev.changedTouches && ev.changedTouches[0]) { return ev.changedTouches[0].clientX; }1332
return ev.clientX;1333
}1334
function pos(ev)1335
{1336
var r = track.getBoundingClientRect();1337
var x = clientX(ev) - r.left;1338
var t = r.width <= 0 ? 0 : x / r.width;1339
var n = App.spendEvents(App.game).length;1340
return Rules.timelineIndex(t, n);1341
}1342
function go(ev, scrub)1343
{1344
if (!App.game) { return; }1345
// Click/tap: jump to the nearest event. Drag: scrub through them.1346
App.jumpReplay(pos(ev), { animate: false, scrub: !!scrub });1347
}1348
function down(e)1349
{1350
if (e.button != null && e.button !== 0) { return; }1351
dragging = true;1352
if (track.setPointerCapture && e.pointerId != null)1353
{1354
try { track.setPointerCapture(e.pointerId); } catch (err) {}1355
}1356
if (e.preventDefault) { e.preventDefault(); }1357
go(e, false);1358
}1359
function move(e)1360
{1361
if (!dragging) { return; }1362
if (e.preventDefault) { e.preventDefault(); }1363
go(e, true);1364
}1365
function up() { dragging = false; }1366
track.addEventListener('pointerdown', down);1367
track.addEventListener('pointermove', move);1368
track.addEventListener('pointerup', up);1369
track.addEventListener('pointercancel', up);1370
// Fallback for older browsers / mixed input: same handlers on touch.1371
track.addEventListener('touchstart', down, { passive: false });1372
track.addEventListener('touchmove', move, { passive: false });1373
track.addEventListener('touchend', up);1374
track.addEventListener('touchcancel', up);1375
};1376
1377
App.toggleReplay = function ()1378
{1379
if (App.replay && App.replay.timer)1380
{1381
clearInterval(App.replay.timer);1382
App.replay.timer = null;1383
this.renderTimeline(App.game);1384
return;1385
}1386
var n = this.spendEvents(App.game).length;1387
if (!n) { return; }1388
var startAt = (App.replay && App.replay.index < n) ? App.replay.index : 0;1389
this.jumpReplay(startAt);1390
App.replay.timer = setInterval(function ()1391
{1392
if (!App.replay) { return; }1393
if (App.replay.index >= n)1394
{1395
App.stopReplay();1396
return;1397
}1398
App.jumpReplay(App.replay.index + 1);1399
}, 500);1400
this.renderTimeline(App.game);1401
};1402
1403
App.jumpReplay = function (index, opts)1404
{1405
opts = opts || {};1406
var game = App.game;1407
var spends = this.spendEvents(game);1408
var n = spends.length;1409
index = Math.max(0, Math.min(n, index));1410
var prev = App.replay && App.replay.view;1411
var prevIndex = App.replay ? App.replay.index : null;1412
var view = this.viewAtSpend(game, index);1413
if (!App.replay) { App.replay = { timer: null }; }1414
var stepping = prevIndex != null && index === prevIndex + 1;1415
var animate = opts.animate !== false && (opts.animate || (App.replay.timer && stepping));1416
App.replay.index = index;1417
App.replay.view = view;1418
this.renderBoard(view);1419
this.renderHud(view);1420
this.renderJury(view);1421
this.renderTimeline(game);1422
this.setCaption();1423
var ev = index > 0 ? spends[index - 1] : null;1424
this.playBoardFx(view, ev, prev, !!animate);1425
};1426
1427
App.viewAtSpend = function (game, spendCount)1428
{1429
// Walk a shallow clone of players from the start event / initial, applying1430
// events until `spendCount` spend-ticks have been applied.1431
var players = (game.players || []).map(function (p)1432
{1433
return Object.assign({}, p);1434
});1435
// Remember which numeric stats the server hid from this viewer, so replay1436
// never invents values the live state would not show.1437
var hidden = {};1438
players.forEach(function (p)1439
{1440
hidden[p.id] = { lives: p.lives == null, ap: p.ap == null, range: p.range == null };1441
});1442
var events = game.events || [];1443
var applied = 0;1444
var start = events.filter(function (e) { return e.type === 'start'; })[0];1445
if (start && start.players)1446
{1447
start.players.forEach(function (sp)1448
{1449
players.forEach(function (p)1450
{1451
if (p.id === sp.id)1452
{1453
p.x = sp.x; p.y = sp.y;1454
if (!hidden[p.id] || !hidden[p.id].lives) { p.lives = 3; }1455
if (!hidden[p.id] || !hidden[p.id].ap) { p.ap = 1; }1456
if (!hidden[p.id] || !hidden[p.id].range) { p.range = 2; }1457
p.alive = true; p.surrendered = false;1458
}1459
});1460
});1461
}1462
var inset = 0;1463
var day = 0;1464
function apply(ev)1465
{1466
var p;1467
if (ev.type === 'move')1468
{1469
p = findIn(players, ev.player);1470
if (p && ev.to) { p.x = ev.to.x; p.y = ev.to.y; if (p.ap > 0) { p.ap--; } }1471
}1472
else if (ev.type === 'shoot')1473
{1474
p = findIn(players, ev.player);1475
if (p && p.ap != null && p.ap > 0) { p.ap--; }1476
var t = findIn(players, ev.target);1477
if (t)1478
{1479
if (ev.lives_left != null && t.lives != null) { t.lives = ev.lives_left; }1480
if (ev.killed)1481
{1482
t.alive = false;1483
if (t.ap != null) { t.ap = 0; }1484
if (t.lives != null) { t.lives = 0; }1485
}1486
}1487
}1488
else if (ev.type === 'give')1489
{1490
p = ev.player ? findIn(players, ev.player) : null;1491
var t2 = findIn(players, ev.target);1492
if (p && p.ap != null) { p.ap = Math.max(0, p.ap - (ev.amount || 1)); }1493
if (t2 && t2.ap != null) { t2.ap += (ev.amount || 1); }1494
}1495
else if (ev.type === 'upgrade')1496
{1497
p = findIn(players, ev.player);1498
if (p)1499
{1500
if (p.range != null && ev.range != null) { p.range = ev.range; }1501
if (p.ap != null && p.ap > 0) { p.ap--; }1502
}1503
}1504
else if (ev.type === 'surrender')1505
{1506
p = findIn(players, ev.player);1507
if (p) { p.alive = false; p.surrendered = true; p.lives = 0; p.ap = 0; }1508
}1509
else if (ev.type === 'daily' && ev.grants)1510
{1511
day = ev.day || day;1512
players.forEach(function (pl)1513
{1514
if (ev.grants[pl.id]) { pl.ap += ev.grants[pl.id]; }1515
});1516
}1517
else if (ev.type === 'shrink')1518
{1519
inset = ev.inset || inset;1520
(ev.moved || []).forEach(function (m)1521
{1522
var q = findIn(players, m.id);1523
if (q && m.to) { q.x = m.to.x; q.y = m.to.y; if (q.lives > 0 && ev.hurt && ev.hurt.indexOf(m.id) >= 0) { /* already in lives? */ } }1524
});1525
(ev.hurt || []).forEach(function (id)1526
{1527
var q = findIn(players, id);1528
if (q && ev.killed && ev.killed.indexOf(id) < 0 && q.lives > 0) { q.lives = Math.max(1, q.lives); }1529
});1530
(ev.killed || []).forEach(function (id)1531
{1532
var q = findIn(players, id);1533
if (q) { q.alive = false; q.lives = 0; q.ap = 0; }1534
});1535
}1536
}1537
for (var i = 0; i < events.length; i++)1538
{1539
var ev = events[i];1540
if (ev.spend)1541
{1542
if (applied >= spendCount) { break; }1543
apply(ev);1544
applied++;1545
}1546
else1547
{1548
// Apply non-spend events that occurred before this point (start,1549
// daily, shrink, death) — only those before the next unapplied spend.1550
// If we have already reached the target spend count, stop before later dailies.1551
if (applied >= spendCount && ev.type !== 'start') { continue; }1552
apply(ev);1553
}1554
}1555
players.forEach(function (p)1556
{1557
var h = hidden[p.id];1558
if (!h) { return; }1559
if (h.lives) { p.lives = null; }1560
if (h.ap) { p.ap = null; }1561
if (h.range) { p.range = null; }1562
});1563
return {1564
you: game.you,1565
players: players,1566
grid: game.grid,1567
arena_inset: inset,1568
max_inset: game.max_inset,1569
shrink_in_days: null,1570
rules: game.rules,1571
legal: { move: [], shoot: [], give: [], upgrade: false, vote: null },1572
day: day,1573
status: game.status,1574
winner_id: null,1575
draw: false,1576
next_distribution_at: null,1577
ceasefire: null1578
};1579
};1580
1581
App.stopReplay = function ()1582
{1583
if (App.replay && App.replay.timer)1584
{ clearInterval(App.replay.timer); }1585
App.replay = null;1586
this.clearBoardFx();1587
if (App.game && App.screen === 'game')1588
{1589
this.renderGame();1590
}1591
};1592
1593
App.clearBoardFx = function ()1594
{1595
var fx = $('board-fx');1596
if (fx) { fx.innerHTML = ''; }1597
var wrap = $('board-wrap');1598
if (wrap)1599
{1600
wrap.querySelectorAll('.fx-float').forEach(function (n) { n.remove(); });1601
}1602
document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse, #board .piece-initials.moving, #board .piece-initials.range-pulse').forEach(function (el)1603
{1604
el.classList.remove('moving', 'range-pulse');1605
el.style.transform = '';1606
el.style.transition = '';1607
});1608
};1609
1610
App.cellCenter = function (x, y)1611
{1612
var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');1613
var wrap = $('board-wrap');1614
if (!cell || !wrap) { return null; }1615
var wr = wrap.getBoundingClientRect();1616
var r = cell.getBoundingClientRect();1617
return {1618
x: r.left + r.width / 2 - wr.left,1619
y: r.top + r.height / 2 - wr.top,1620
s: Math.min(r.width, r.height)1621
};1622
};1623
1624
App.playerCell = function (view, id)1625
{1626
var p = findIn(view && view.players, id);1627
if (!p) { return null; }1628
return App.cellCenter(p.x, p.y);1629
};1630
1631
App.pieceInCell = function (x, y)1632
{1633
var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');1634
return cell ? cell.querySelector('.piece, .piece-initials') : null;1635
};1636
1637
App.playBoardFx = function (view, ev, prev, animate)1638
{1639
this.clearBoardFx();1640
if (!ev || !view) { return; }1641
var wrap = $('board-wrap');1642
var fx = $('board-fx');1643
if (!wrap || !fx) { return; }1644
fx.setAttribute('width', String(wrap.clientWidth));1645
fx.setAttribute('height', String(wrap.clientHeight));1646
fx.setAttribute('viewBox', '0 0 ' + wrap.clientWidth + ' ' + wrap.clientHeight);1647
1648
if (ev.type === 'shoot' && ev.target)1649
{1650
var from = ev.player ? App.playerCell(prev || view, ev.player) : null;1651
var to = App.playerCell(view, ev.target);1652
// If the shooter is known (not filtered), draw a red arrow; the number1653
// is damage, not remaining lives, so it does not leak hidden life totals.1654
if (from && to && ev.player)1655
{1656
App.drawArrow(from, to, '#e85d5d', ev.damage != null ? ev.damage : 1);1657
}1658
else if (to)1659
{1660
App.floatNumber(to, ev.damage != null ? ev.damage : 1, '#e85d5d');1661
}1662
if (ev.loot && ev.player)1663
{1664
var lootAt = App.playerCell(view, ev.player);1665
if (lootAt) { App.floatNumber(lootAt, '+' + ev.loot, '#4ecb8d'); }1666
}1667
}1668
else if (ev.type === 'give')1669
{1670
var tTo = ev.target ? App.playerCell(view, ev.target) : null;1671
var amount = ev.amount != null ? ev.amount : 1;1672
if (ev.anonymous || !ev.player)1673
{1674
// Must not reveal the giver: show the AP gain on the recipient only,1675
// with no source arrow (an arrow "from nowhere" would still suggest a direction).1676
if (tTo) { App.floatNumber(tTo, '+' + amount, '#4ecb8d'); }1677
}1678
else1679
{1680
var gFrom = App.playerCell(prev || view, ev.player);1681
if (gFrom && tTo)1682
{1683
App.drawArrow(gFrom, tTo, '#4ecb8d', amount);1684
}1685
else if (tTo)1686
{1687
App.floatNumber(tTo, '+' + amount, '#4ecb8d');1688
}1689
}1690
}1691
else if (ev.type === 'move' && ev.to && ev.from && ev.player && animate)1692
{1693
App.animateMove(ev.from, ev.to);1694
}1695
else if (ev.type === 'upgrade' && ev.player)1696
{1697
var p = findIn(view.players, ev.player);1698
if (p)1699
{1700
var piece = App.pieceInCell(p.x, p.y);1701
if (piece)1702
{1703
piece.classList.remove('range-pulse');1704
void piece.offsetWidth;1705
piece.classList.add('range-pulse');1706
}1707
}1708
}1709
};1710
1711
App.drawArrow = function (from, to, color, number)1712
{1713
var fx = $('board-fx');1714
if (!fx || !from || !to) { return; }1715
var ns = 'http://www.w3.org/2000/svg';1716
var dx = to.x - from.x, dy = to.y - from.y;1717
var len = Math.sqrt(dx * dx + dy * dy) || 1;1718
var ux = dx / len, uy = dy / len;1719
var inset = Math.min(from.s || 24, to.s || 24) * 0.38;1720
if (inset * 2 >= len) { inset = len * 0.22; }1721
var x1 = from.x + ux * inset, y1 = from.y + uy * inset;1722
var x2 = to.x - ux * inset, y2 = to.y - uy * inset;1723
var mid = 'm' + Math.round(x1) + '-' + Math.round(y1) + '-' + Math.round(x2) + '-' + Math.round(y2);1724
var defs = document.createElementNS(ns, 'defs');1725
var marker = document.createElementNS(ns, 'marker');1726
marker.setAttribute('id', mid);1727
marker.setAttribute('viewBox', '0 0 10 10');1728
marker.setAttribute('refX', '8');1729
marker.setAttribute('refY', '5');1730
marker.setAttribute('markerWidth', '7');1731
marker.setAttribute('markerHeight', '7');1732
marker.setAttribute('orient', 'auto');1733
var tip = document.createElementNS(ns, 'path');1734
tip.setAttribute('d', 'M 0 0 L 10 5 L 0 10 z');1735
tip.setAttribute('fill', color);1736
marker.appendChild(tip);1737
defs.appendChild(marker);1738
fx.appendChild(defs);1739
var line = document.createElementNS(ns, 'line');1740
line.setAttribute('x1', String(x1));1741
line.setAttribute('y1', String(y1));1742
line.setAttribute('x2', String(x2));1743
line.setAttribute('y2', String(y2));1744
line.setAttribute('stroke', color);1745
line.setAttribute('stroke-width', '4');1746
line.setAttribute('stroke-linecap', 'round');1747
line.setAttribute('marker-end', 'url(#' + mid + ')');1748
fx.appendChild(line);1749
if (number != null && number !== '')1750
{1751
var mx = x1 + (x2 - x1) * 0.55;1752
var my = y1 + (y2 - y1) * 0.55;1753
var circ = document.createElementNS(ns, 'circle');1754
circ.setAttribute('cx', String(mx));1755
circ.setAttribute('cy', String(my));1756
circ.setAttribute('r', '13');1757
circ.setAttribute('fill', color);1758
circ.setAttribute('stroke', '#0c1020');1759
circ.setAttribute('stroke-width', '2');1760
fx.appendChild(circ);1761
var tx = document.createElementNS(ns, 'text');1762
tx.setAttribute('x', String(mx));1763
tx.setAttribute('y', String(my + 1));1764
tx.setAttribute('text-anchor', 'middle');1765
tx.setAttribute('dominant-baseline', 'middle');1766
tx.setAttribute('fill', '#fff');1767
tx.setAttribute('font-size', '13');1768
tx.setAttribute('font-weight', '700');1769
tx.setAttribute('font-family', 'ui-sans-serif, system-ui, sans-serif');1770
tx.textContent = String(number);1771
fx.appendChild(tx);1772
}1773
};1774
1775
App.floatNumber = function (at, text, color)1776
{1777
var wrap = $('board-wrap');1778
if (!wrap || !at) { return; }1779
var el = document.createElement('div');1780
el.className = 'fx-float';1781
el.textContent = String(text);1782
el.style.left = at.x + 'px';1783
el.style.top = at.y + 'px';1784
if (color) { el.style.color = color; }1785
wrap.appendChild(el);1786
};1787
1788
App.animateMove = function (from, to)1789
{1790
var piece = App.pieceInCell(to.x, to.y);1791
var a = App.cellCenter(from.x, from.y);1792
var b = App.cellCenter(to.x, to.y);1793
if (!piece || !a || !b) { return; }1794
var dx = a.x - b.x, dy = a.y - b.y;1795
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) { return; }1796
piece.classList.add('moving');1797
piece.style.transition = 'none';1798
piece.style.transform = 'translate(' + dx + 'px, ' + dy + 'px)';1799
requestAnimationFrame(function ()1800
{1801
requestAnimationFrame(function ()1802
{1803
piece.style.transition = 'transform 0.4s ease';1804
piece.style.transform = 'translate(0, 0)';1805
});1806
});1807
};1808
1809
1810
function escapeHtml(s)1811
{1812
return String(s).replace(/[&<>"']/g, function (c)1813
{1814
return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c];1815
});1816
}1817
1818
/* ---------- 24-hour cease-fire clock ---------- */1819
1820
var CeasefireClock = {1821
size: 320,1822
cx: 160,1823
cy: 160,1824
r: 1281825
};1826
1827
CeasefireClock.minsToAngle = function (mins)1828
{1829
// 0 at top, clockwise, 1440 minutes = 360°.1830
return (mins / 1440) * 2 * Math.PI - Math.PI / 2;1831
};1832
1833
CeasefireClock.angleToMins = function (ang)1834
{1835
// atan2: 0 at 3 o'clock, CCW. Convert to clockwise from top.1836
var a = ang + Math.PI / 2;1837
if (a < 0) { a += 2 * Math.PI; }1838
var mins = Math.round((a / (2 * Math.PI)) * 1440 / 5) * 5;1839
if (mins >= 1440) { mins = 0; }1840
if (mins < 0) { mins = 0; }1841
return mins;1842
};1843
1844
CeasefireClock.arcPath = function (r, startMin, endMin)1845
{1846
var cx = this.cx, cy = this.cy;1847
var a1 = this.minsToAngle(startMin);1848
var a2 = this.minsToAngle(endMin);1849
var x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1);1850
var x2 = cx + r * Math.cos(a2), y2 = cy + r * Math.sin(a2);1851
var delta = endMin - startMin;1852
if (delta <= 0) { delta += 1440; }1853
var large = delta > 720 ? 1 : 0;1854
return 'M ' + cx + ' ' + cy + ' L ' + x1 + ' ' + y1 + ' A ' + r + ' ' + r + ' 0 ' + large + ' 1 ' + x2 + ' ' + y2 + ' Z';1855
};1856
1857
CeasefireClock.handlePos = function (mins)1858
{1859
var a = this.minsToAngle(mins);1860
return { x: this.cx + this.r * Math.cos(a), y: this.cy + this.r * Math.sin(a) };1861
};1862
1863
CeasefireClock.render = function (container, ranges, opts)1864
{1865
opts = opts || {};1866
var self = this;1867
ranges = Rules.normalizeRanges(ranges || []);1868
var size = this.size;1869
var svgNS = 'http://www.w3.org/2000/svg';1870
container.innerHTML = '';1871
var svg = document.createElementNS(svgNS, 'svg');1872
svg.setAttribute('viewBox', '0 0 ' + size + ' ' + size);1873
svg.setAttribute('width', String(size));1874
svg.setAttribute('height', String(size));1875
svg.setAttribute('role', 'img');1876
1877
function el(name, attrs)1878
{1879
var n = document.createElementNS(svgNS, name);1880
Object.keys(attrs).forEach(function (k) { n.setAttribute(k, attrs[k]); });1881
return n;1882
}1883
1884
// Allowed (gold) background disc1885
svg.appendChild(el('circle', {1886
cx: this.cx, cy: this.cy, r: this.r,1887
fill: '#3a3420', stroke: '#e8c547', 'stroke-width': '3'1888
}));1889
1890
// Cease-fire slices (red)1891
ranges.forEach(function (r, i)1892
{1893
var s = Rules.hmToMinutes(r.start);1894
var e = Rules.hmToMinutes(r.end);1895
var slices = e > s ? [[s, e]] : [[s, 1440], [0, e]];1896
slices.forEach(function (sl)1897
{1898
if (sl[1] === sl[0]) { return; }1899
svg.appendChild(el('path', {1900
d: self.arcPath(self.r - 1, sl[0], sl[1]),1901
fill: '#8a2a2a',1902
'fill-opacity': '0.92',1903
'data-range': String(i)1904
}));1905
});1906
});1907
1908
// Ticks and labels (0 at top, then 3, 6, 12, 18…)1909
for (var h = 0; h < 24; h++)1910
{1911
var mins = h * 60;1912
var a = this.minsToAngle(mins);1913
var inner = this.r - (h % 3 === 0 ? 14 : 7);1914
var outer = this.r;1915
svg.appendChild(el('line', {1916
x1: this.cx + inner * Math.cos(a),1917
y1: this.cy + inner * Math.sin(a),1918
x2: this.cx + outer * Math.cos(a),1919
y2: this.cy + outer * Math.sin(a),1920
stroke: '#e8eaf2',1921
'stroke-width': h % 6 === 0 ? '2.2' : '1',1922
'stroke-opacity': '0.7'1923
}));1924
if (h % 3 === 0)1925
{1926
var tx = this.cx + (this.r + 22) * Math.cos(a);1927
var ty = this.cy + (this.r + 22) * Math.sin(a);1928
var lab = el('text', {1929
x: tx, y: ty,1930
fill: '#e8c547',1931
'font-size': '13',1932
'font-weight': '700',1933
'text-anchor': 'middle',1934
'dominant-baseline': 'middle',1935
'pointer-events': 'none'1936
});1937
lab.textContent = String(h);1938
svg.appendChild(lab);1939
}1940
}1941
1942
// Inner hole so it looks like a ring-pie (keep a smaller gold disc for “now” later)1943
svg.appendChild(el('circle', {1944
cx: this.cx, cy: this.cy, r: 36,1945
fill: '#0c1020', stroke: '#e8c54755', 'stroke-width': '1.5'1946
}));1947
var mid = el('text', {1948
x: this.cx, y: this.cy + 1,1949
fill: '#e8eaf2',1950
'font-size': '11',1951
'text-anchor': 'middle',1952
'dominant-baseline': 'middle',1953
'pointer-events': 'none'1954
});1955
mid.textContent = '24h';1956
svg.appendChild(mid);1957
1958
// Handles1959
if (opts.editable)1960
{1961
ranges.forEach(function (r, i)1962
{1963
['start', 'end'].forEach(function (which)1964
{1965
var pos = self.handlePos(Rules.hmToMinutes(r[which]));1966
var c = el('circle', {1967
cx: pos.x, cy: pos.y, r: 14,1968
fill: '#e8c547',1969
stroke: '#1a1404',1970
'stroke-width': '2',1971
'data-range': String(i),1972
'data-which': which,1973
style: 'cursor:grab; touch-action:none'1974
});1975
// invisible larger hit target1976
var hit = el('circle', {1977
cx: pos.x, cy: pos.y, r: 22,1978
fill: 'transparent',1979
'data-range': String(i),1980
'data-which': which,1981
style: 'cursor:grab; touch-action:none'1982
});1983
svg.appendChild(hit);1984
svg.appendChild(c);1985
});1986
});1987
}1988
1989
container.appendChild(svg);1990
if (!opts.editable) { return; }1991
1992
var drag = null;1993
var painting = null;1994
1995
function localMins(ev)1996
{1997
var rect = svg.getBoundingClientRect();1998
var cx = ev.clientX != null ? ev.clientX : ev.touches[0].clientX;1999
var cy = ev.clientY != null ? ev.clientY : ev.touches[0].clientY;2000
var x = (cx - rect.left) / rect.width * size;2001
var y = (cy - rect.top) / rect.height * size;2002
return self.angleToMins(Math.atan2(y - self.cy, x - self.cx));2003
}2004
2005
function commit(next)2006
{2007
if (opts.onChange) { opts.onChange(next); }2008
}2009
2010
svg.addEventListener('pointerdown', function (e)2011
{2012
e.preventDefault();2013
svg.setPointerCapture(e.pointerId);2014
var t = e.target;2015
var ri = t.getAttribute && t.getAttribute('data-range');2016
var which = t.getAttribute && t.getAttribute('data-which');2017
if (ri != null && which)2018
{2019
drag = { i: parseInt(ri, 10), which: which };2020
return;2021
}2022
// Start a new range from this angle, drag to set the end.2023
var m = localMins(e);2024
painting = { start: m, end: (m + 60) % 1440 };2025
});2026
svg.addEventListener('pointermove', function (e)2027
{2028
if (!drag && !painting) { return; }2029
e.preventDefault();2030
var m = localMins(e);2031
if (drag)2032
{2033
var next = ranges.map(function (r) { return { start: r.start, end: r.end }; });2034
if (!next[drag.i]) { return; }2035
next[drag.i][drag.which] = Rules.minutesToHm(m);2036
// Live preview2037
self.render(container, next, opts);2038
// re-bind happens via render → we need to keep dragging. Store on object.2039
CeasefireClock._pending = { drag: drag, ranges: next, opts: opts, container: container };2040
}2041
else if (painting)2042
{2043
painting.end = m;2044
var preview = ranges.concat([{2045
start: Rules.minutesToHm(painting.start),2046
end: Rules.minutesToHm(painting.end === painting.start ? (painting.start + 5) % 1440 : painting.end)2047
}]);2048
self.render(container, preview, opts);2049
CeasefireClock._pending = { painting: painting, ranges: ranges, opts: opts, container: container };2050
}2051
});2052
function endDrag(e)2053
{2054
var pending = CeasefireClock._pending;2055
CeasefireClock._pending = null;2056
if (drag && pending && pending.ranges)2057
{2058
var d = drag;2059
drag = null;2060
commit(pending.ranges);2061
return;2062
}2063
if (painting)2064
{2065
var p = painting;2066
painting = null;2067
if (p.start === p.end) { self.render(container, ranges, opts); return; }2068
commit(ranges.concat([{2069
start: Rules.minutesToHm(p.start),2070
end: Rules.minutesToHm(p.end)2071
}]));2072
}2073
drag = null;2074
}2075
svg.addEventListener('pointerup', endDrag);2076
svg.addEventListener('pointercancel', endDrag);2077
};2078
2079
// Re-attach pointer handlers after a live-preview re-render by using2080
// event delegation on the container (already on svg after each render).2081
// The _pending flag lets pointermove after re-render continue: we also2082
// bind at the document level during a drag.2083
(function ()2084
{2085
var active = false;2086
document.addEventListener('pointermove', function (e)2087
{2088
var p = CeasefireClock._pending;2089
if (!p || !p.opts) { return; }2090
if (!p.drag && !p.painting) { return; }2091
// The new svg already has handlers; this is a safety net no-op if they fire.2092
});2093
})();2094
2095
/* boot */2096
if (typeof document !== 'undefined')2097
{2098
if (document.readyState === 'loading')2099
{ document.addEventListener('DOMContentLoaded', function () { App.init(); }); }2100
else2101
{ App.init(); }2102
}2103
2104
if (typeof module !== 'undefined' && module.exports)2105
{ module.exports = { App: App, CeasefireClock: CeasefireClock, Rules: (typeof Rules !== 'undefined' ? Rules : null) }; }@@ -0,0 +1,284 @@
1
'use strict';
2
3
/**
4
* Client-side mirror of the Allianties rule helpers.
5
* Used for legal-move previews, the cease-fire clock, countdowns, and tests.
6
* The server (Engine.php) is authoritative for every action.
7
*/
8
var Rules = {
9
TZ: 'Europe/Amsterdam',
10
STARTING_LIVES: 3,
11
STARTING_RANGE: 2,
12
STARTING_AP: 1,
13
MIN_PLAYERS: 2,
14
MAX_PLAYERS: 16,
15
MIN_GRID: 6,
16
MIN_ARENA: 3,
17
DEFAULT_SHRINK_DAYS: 7,
18
COLORS: [
19
'#e74c3c', '#3498db', '#2ecc71', '#f1c40f',
20
'#9b59b6', '#e67e22', '#1abc9c', '#e91e63',
21
'#00bcd4', '#8bc34a', '#ff5722', '#3f51b5',
22
'#795548', '#607d8b', '#cddc39', '#ff9800'
23
]
24
};
25
26
Rules.defaultRules = function ()
27
{
28
return {
29
jury: true,
30
shrinking_arena: false,
31
shrink_interval_days: this.DEFAULT_SHRINK_DAYS,
32
ceasefire: false,
33
ceasefire_ranges: [],
34
ap_loot: false,
35
ap_time: '00:00',
36
vis_shots: 'public',
37
vis_gifts: 'public',
38
vis_ap: 'public',
39
vis_range: 'public',
40
vis_lives: 'public'
41
};
42
};
43
44
Rules.gridSize = function (n)
45
{
46
if (n < 1) { n = 1; }
47
return Math.max(this.MIN_GRID, Math.ceil(Math.sqrt(n * 6)));
48
};
49
50
Rules.maxInset = function (size)
51
{
52
return Math.max(0, Math.floor((size - this.MIN_ARENA) / 2));
53
};
54
55
Rules.chebyshev = function (x1, y1, x2, y2)
56
{
57
return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2));
58
};
59
60
Rules.inBounds = function (size, x, y)
61
{
62
return x >= 0 && y >= 0 && x < size && y < size;
63
};
64
65
Rules.isPassable = function (size, inset, x, y)
66
{
67
return this.inBounds(size, x, y)
68
&& x >= inset && y >= inset && x < size - inset && y < size - inset;
69
};
70
71
Rules.parseHm = function (v)
72
{
73
if (typeof v !== 'string') { return null; }
74
var m = /^(\d{1,2}):(\d{2})$/.exec(v.trim());
75
if (!m) { return null; }
76
var h = parseInt(m[1], 10), min = parseInt(m[2], 10);
77
if (h > 23 || min > 59) { return null; }
78
return (h < 10 ? '0' : '') + h + ':' + (min < 10 ? '0' : '') + min;
79
};
80
81
Rules.hmToMinutes = function (hm)
82
{
83
var p = hm.split(':');
84
return parseInt(p[0], 10) * 60 + parseInt(p[1], 10);
85
};
86
87
Rules.minutesToHm = function (mins)
88
{
89
mins = ((mins % 1440) + 1440) % 1440;
90
var h = Math.floor(mins / 60), m = mins % 60;
91
return (h < 10 ? '0' : '') + h + ':' + (m < 10 ? '0' : '') + m;
92
};
93
94
Rules.normalizeRanges = function (raw)
95
{
96
if (!Array.isArray(raw)) { return []; }
97
var out = [], seen = {};
98
for (var i = 0; i < raw.length; i++)
99
{
100
var r = raw[i];
101
if (!r) { continue; }
102
var start = this.parseHm(r.start || r[0]);
103
var end = this.parseHm(r.end || r[1]);
104
if (!start || !end || start === end) { continue; }
105
var key = start + '-' + end;
106
if (seen[key]) { continue; }
107
seen[key] = true;
108
out.push({ start: start, end: end });
109
}
110
out.sort(function (a, b) { return a.start < b.start ? -1 : a.start > b.start ? 1 : 0; });
111
return out.slice(0, 12);
112
};
113
114
/** Unix timestamp of ymd 00:00 in Europe/Amsterdam. */
115
Rules.amsterdamMidnight = function (ymd)
116
{
117
var parts = ymd.split('-').map(Number);
118
var Y = parts[0], M = parts[1], D = parts[2];
119
// First guess: UTC midnight minus one hour (CET).
120
var utc = Date.UTC(Y, M - 1, D, 0, 0, 0) - 3600 * 1000;
121
for (var i = 0; i < 5; i++)
122
{
123
var p = this._amsterdamParts(utc);
124
var got = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +(p.second || 0));
125
var want = Date.UTC(Y, M - 1, D, 0, 0, 0);
126
utc += (want - got);
127
}
128
return Math.floor(utc / 1000);
129
};
130
131
Rules._amsterdamParts = function (unixMs)
132
{
133
var fmt = new Intl.DateTimeFormat('en-US', {
134
timeZone: 'Europe/Amsterdam',
135
year: 'numeric', month: '2-digit', day: '2-digit',
136
hour: '2-digit', minute: '2-digit', second: '2-digit',
137
hourCycle: 'h23'
138
});
139
var p = {};
140
fmt.formatToParts(new Date(unixMs)).forEach(function (x)
141
{
142
if (x.type !== 'literal') { p[x.type] = x.value; }
143
});
144
return p;
145
};
146
147
Rules.amsterdamYmd = function (unix)
148
{
149
var p = this._amsterdamParts(unix * 1000);
150
return p.year + '-' + p.month + '-' + p.day;
151
};
152
153
/**
154
* Wall-clock HH:MM on a civil date in Europe/Amsterdam, as unix seconds.
155
* Matches PHP DateTime::modify("+N minutes") from midnight: civil minutes
156
* walk through DST (spring-forward shortens, fall-back lengthens).
157
* Non-existent times (e.g. 02:30 on a spring-forward day) land after the gap.
158
*/
159
Rules.amsterdamWallclock = function (ymd, hm)
160
{
161
var t = this.amsterdamMidnight(ymd);
162
var target = this.hmToMinutes(hm);
163
if (target === 0)
164
{ return t; }
165
for (var i = 0; i < 8; i++)
166
{
167
var p = this._amsterdamParts(t * 1000);
168
var day = p.year + '-' + p.month + '-' + p.day;
169
var got = (+p.hour) * 60 + (+p.minute);
170
if (day !== ymd)
171
{
172
// Overflowed into another civil day (should be rare for HH:MM).
173
var sign = day > ymd ? 1 : -1;
174
got += sign * 1440;
175
}
176
var remaining = target - got;
177
if (remaining === 0)
178
{ return t; }
179
// If we oscillate around a spring-forward gap, take the later side.
180
t += remaining * 60;
181
}
182
return t;
183
};
184
185
Rules.addDaysYmd = function (ymd, days)
186
{
187
// Add calendar days via Amsterdam midnight + 26h, then read the ymd and
188
// correct — safer: midnight + days*24h may skip/double; use Date in UTC
189
// of the civil date then shift.
190
var p = ymd.split('-').map(Number);
191
var d = new Date(Date.UTC(p[0], p[1] - 1, p[2] + days));
192
var mm = d.getUTCMonth() + 1, dd = d.getUTCDate();
193
return d.getUTCFullYear() + '-' + (mm < 10 ? '0' : '') + mm + '-' + (dd < 10 ? '0' : '') + dd;
194
};
195
196
Rules.ceasefireIntervals = function (ranges, now)
197
{
198
ranges = this.normalizeRanges(ranges);
199
if (!ranges.length) { return []; }
200
var anchor = this.amsterdamYmd(now);
201
var intervals = [];
202
for (var d = -1; d <= 3; d++)
203
{
204
var ymd = this.addDaysYmd(anchor, d);
205
var next = this.addDaysYmd(anchor, d + 1);
206
for (var i = 0; i < ranges.length; i++)
207
{
208
var r = ranges[i];
209
var startM = this.hmToMinutes(r.start);
210
var endM = this.hmToMinutes(r.end);
211
var startTs = this.amsterdamWallclock(ymd, r.start);
212
var endTs = endM > startM
213
? this.amsterdamWallclock(ymd, r.end)
214
: this.amsterdamWallclock(next, r.end);
215
if (endTs > startTs) { intervals.push([startTs, endTs]); }
216
}
217
}
218
intervals.sort(function (a, b) { return a[0] - b[0] || a[1] - b[1]; });
219
var merged = [];
220
for (var j = 0; j < intervals.length; j++)
221
{
222
var iv = intervals[j];
223
if (!merged.length || iv[0] > merged[merged.length - 1][1])
224
{ merged.push(iv.slice()); }
225
else
226
{ merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], iv[1]); }
227
}
228
return merged;
229
};
230
231
Rules.ceasefireInfo = function (rules, now)
232
{
233
if (!rules || !rules.ceasefire) { return null; }
234
var ranges = this.normalizeRanges(rules.ceasefire_ranges);
235
if (!ranges.length) { return null; }
236
var intervals = this.ceasefireIntervals(ranges, now);
237
var active = false, until = null;
238
for (var i = 0; i < intervals.length; i++)
239
{
240
var iv = intervals[i];
241
if (now >= iv[0] && now < iv[1])
242
{
243
active = true;
244
until = iv[1];
245
break;
246
}
247
if (iv[0] > now && (until === null || iv[0] < until))
248
{ until = iv[0]; }
249
}
250
return {
251
enabled: true,
252
active: active,
253
until: until,
254
seconds: until !== null ? Math.max(0, until - now) : 0,
255
ranges: ranges
256
};
257
};
258
259
Rules.formatHms = function (seconds)
260
{
261
seconds = Math.max(0, Math.floor(seconds));
262
var h = Math.floor(seconds / 3600);
263
var m = Math.floor((seconds % 3600) / 60);
264
var s = seconds % 60;
265
function pad (n) { return n < 10 ? '0' + n : String(n); }
266
return pad(h) + ':' + pad(m) + ':' + pad(s);
267
};
268
269
if (typeof module !== 'undefined' && module.exports)
270
{ module.exports = Rules; }
271
else if (typeof globalThis !== 'undefined')
272
{ globalThis.Rules = Rules; }
273
274
/**
275
* Map a 0–1 position along the timeline track to a spend index 0..n
276
* (0 = before the first spend, n = after the last / live). Nearest event.
277
*/
278
Rules.timelineIndex = function (t, n)
279
{
280
n = n | 0;
281
if (n <= 0) { return 0; }
282
t = Math.max(0, Math.min(1, Number(t) || 0));
283
return Math.round(t * n);
284
};
@@ -0,0 +1,284 @@1
'use strict';2
3
/**4
* Client-side mirror of the Allianties rule helpers.5
* Used for legal-move previews, the cease-fire clock, countdowns, and tests.6
* The server (Engine.php) is authoritative for every action.7
*/8
var Rules = {9
TZ: 'Europe/Amsterdam',10
STARTING_LIVES: 3,11
STARTING_RANGE: 2,12
STARTING_AP: 1,13
MIN_PLAYERS: 2,14
MAX_PLAYERS: 16,15
MIN_GRID: 6,16
MIN_ARENA: 3,17
DEFAULT_SHRINK_DAYS: 7,18
COLORS: [19
'#e74c3c', '#3498db', '#2ecc71', '#f1c40f',20
'#9b59b6', '#e67e22', '#1abc9c', '#e91e63',21
'#00bcd4', '#8bc34a', '#ff5722', '#3f51b5',22
'#795548', '#607d8b', '#cddc39', '#ff9800'23
]24
};25
26
Rules.defaultRules = function ()27
{28
return {29
jury: true,30
shrinking_arena: false,31
shrink_interval_days: this.DEFAULT_SHRINK_DAYS,32
ceasefire: false,33
ceasefire_ranges: [],34
ap_loot: false,35
ap_time: '00:00',36
vis_shots: 'public',37
vis_gifts: 'public',38
vis_ap: 'public',39
vis_range: 'public',40
vis_lives: 'public'41
};42
};43
44
Rules.gridSize = function (n)45
{46
if (n < 1) { n = 1; }47
return Math.max(this.MIN_GRID, Math.ceil(Math.sqrt(n * 6)));48
};49
50
Rules.maxInset = function (size)51
{52
return Math.max(0, Math.floor((size - this.MIN_ARENA) / 2));53
};54
55
Rules.chebyshev = function (x1, y1, x2, y2)56
{57
return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2));58
};59
60
Rules.inBounds = function (size, x, y)61
{62
return x >= 0 && y >= 0 && x < size && y < size;63
};64
65
Rules.isPassable = function (size, inset, x, y)66
{67
return this.inBounds(size, x, y)68
&& x >= inset && y >= inset && x < size - inset && y < size - inset;69
};70
71
Rules.parseHm = function (v)72
{73
if (typeof v !== 'string') { return null; }74
var m = /^(\d{1,2}):(\d{2})$/.exec(v.trim());75
if (!m) { return null; }76
var h = parseInt(m[1], 10), min = parseInt(m[2], 10);77
if (h > 23 || min > 59) { return null; }78
return (h < 10 ? '0' : '') + h + ':' + (min < 10 ? '0' : '') + min;79
};80
81
Rules.hmToMinutes = function (hm)82
{83
var p = hm.split(':');84
return parseInt(p[0], 10) * 60 + parseInt(p[1], 10);85
};86
87
Rules.minutesToHm = function (mins)88
{89
mins = ((mins % 1440) + 1440) % 1440;90
var h = Math.floor(mins / 60), m = mins % 60;91
return (h < 10 ? '0' : '') + h + ':' + (m < 10 ? '0' : '') + m;92
};93
94
Rules.normalizeRanges = function (raw)95
{96
if (!Array.isArray(raw)) { return []; }97
var out = [], seen = {};98
for (var i = 0; i < raw.length; i++)99
{100
var r = raw[i];101
if (!r) { continue; }102
var start = this.parseHm(r.start || r[0]);103
var end = this.parseHm(r.end || r[1]);104
if (!start || !end || start === end) { continue; }105
var key = start + '-' + end;106
if (seen[key]) { continue; }107
seen[key] = true;108
out.push({ start: start, end: end });109
}110
out.sort(function (a, b) { return a.start < b.start ? -1 : a.start > b.start ? 1 : 0; });111
return out.slice(0, 12);112
};113
114
/** Unix timestamp of ymd 00:00 in Europe/Amsterdam. */115
Rules.amsterdamMidnight = function (ymd)116
{117
var parts = ymd.split('-').map(Number);118
var Y = parts[0], M = parts[1], D = parts[2];119
// First guess: UTC midnight minus one hour (CET).120
var utc = Date.UTC(Y, M - 1, D, 0, 0, 0) - 3600 * 1000;121
for (var i = 0; i < 5; i++)122
{123
var p = this._amsterdamParts(utc);124
var got = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +(p.second || 0));125
var want = Date.UTC(Y, M - 1, D, 0, 0, 0);126
utc += (want - got);127
}128
return Math.floor(utc / 1000);129
};130
131
Rules._amsterdamParts = function (unixMs)132
{133
var fmt = new Intl.DateTimeFormat('en-US', {134
timeZone: 'Europe/Amsterdam',135
year: 'numeric', month: '2-digit', day: '2-digit',136
hour: '2-digit', minute: '2-digit', second: '2-digit',137
hourCycle: 'h23'138
});139
var p = {};140
fmt.formatToParts(new Date(unixMs)).forEach(function (x)141
{142
if (x.type !== 'literal') { p[x.type] = x.value; }143
});144
return p;145
};146
147
Rules.amsterdamYmd = function (unix)148
{149
var p = this._amsterdamParts(unix * 1000);150
return p.year + '-' + p.month + '-' + p.day;151
};152
153
/**154
* Wall-clock HH:MM on a civil date in Europe/Amsterdam, as unix seconds.155
* Matches PHP DateTime::modify("+N minutes") from midnight: civil minutes156
* walk through DST (spring-forward shortens, fall-back lengthens).157
* Non-existent times (e.g. 02:30 on a spring-forward day) land after the gap.158
*/159
Rules.amsterdamWallclock = function (ymd, hm)160
{161
var t = this.amsterdamMidnight(ymd);162
var target = this.hmToMinutes(hm);163
if (target === 0)164
{ return t; }165
for (var i = 0; i < 8; i++)166
{167
var p = this._amsterdamParts(t * 1000);168
var day = p.year + '-' + p.month + '-' + p.day;169
var got = (+p.hour) * 60 + (+p.minute);170
if (day !== ymd)171
{172
// Overflowed into another civil day (should be rare for HH:MM).173
var sign = day > ymd ? 1 : -1;174
got += sign * 1440;175
}176
var remaining = target - got;177
if (remaining === 0)178
{ return t; }179
// If we oscillate around a spring-forward gap, take the later side.180
t += remaining * 60;181
}182
return t;183
};184
185
Rules.addDaysYmd = function (ymd, days)186
{187
// Add calendar days via Amsterdam midnight + 26h, then read the ymd and188
// correct — safer: midnight + days*24h may skip/double; use Date in UTC189
// of the civil date then shift.190
var p = ymd.split('-').map(Number);191
var d = new Date(Date.UTC(p[0], p[1] - 1, p[2] + days));192
var mm = d.getUTCMonth() + 1, dd = d.getUTCDate();193
return d.getUTCFullYear() + '-' + (mm < 10 ? '0' : '') + mm + '-' + (dd < 10 ? '0' : '') + dd;194
};195
196
Rules.ceasefireIntervals = function (ranges, now)197
{198
ranges = this.normalizeRanges(ranges);199
if (!ranges.length) { return []; }200
var anchor = this.amsterdamYmd(now);201
var intervals = [];202
for (var d = -1; d <= 3; d++)203
{204
var ymd = this.addDaysYmd(anchor, d);205
var next = this.addDaysYmd(anchor, d + 1);206
for (var i = 0; i < ranges.length; i++)207
{208
var r = ranges[i];209
var startM = this.hmToMinutes(r.start);210
var endM = this.hmToMinutes(r.end);211
var startTs = this.amsterdamWallclock(ymd, r.start);212
var endTs = endM > startM213
? this.amsterdamWallclock(ymd, r.end)214
: this.amsterdamWallclock(next, r.end);215
if (endTs > startTs) { intervals.push([startTs, endTs]); }216
}217
}218
intervals.sort(function (a, b) { return a[0] - b[0] || a[1] - b[1]; });219
var merged = [];220
for (var j = 0; j < intervals.length; j++)221
{222
var iv = intervals[j];223
if (!merged.length || iv[0] > merged[merged.length - 1][1])224
{ merged.push(iv.slice()); }225
else226
{ merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], iv[1]); }227
}228
return merged;229
};230
231
Rules.ceasefireInfo = function (rules, now)232
{233
if (!rules || !rules.ceasefire) { return null; }234
var ranges = this.normalizeRanges(rules.ceasefire_ranges);235
if (!ranges.length) { return null; }236
var intervals = this.ceasefireIntervals(ranges, now);237
var active = false, until = null;238
for (var i = 0; i < intervals.length; i++)239
{240
var iv = intervals[i];241
if (now >= iv[0] && now < iv[1])242
{243
active = true;244
until = iv[1];245
break;246
}247
if (iv[0] > now && (until === null || iv[0] < until))248
{ until = iv[0]; }249
}250
return {251
enabled: true,252
active: active,253
until: until,254
seconds: until !== null ? Math.max(0, until - now) : 0,255
ranges: ranges256
};257
};258
259
Rules.formatHms = function (seconds)260
{261
seconds = Math.max(0, Math.floor(seconds));262
var h = Math.floor(seconds / 3600);263
var m = Math.floor((seconds % 3600) / 60);264
var s = seconds % 60;265
function pad (n) { return n < 10 ? '0' + n : String(n); }266
return pad(h) + ':' + pad(m) + ':' + pad(s);267
};268
269
if (typeof module !== 'undefined' && module.exports)270
{ module.exports = Rules; }271
else if (typeof globalThis !== 'undefined')272
{ globalThis.Rules = Rules; }273
274
/**275
* Map a 0–1 position along the timeline track to a spend index 0..n276
* (0 = before the first spend, n = after the last / live). Nearest event.277
*/278
Rules.timelineIndex = function (t, n)279
{280
n = n | 0;281
if (n <= 0) { return 0; }282
t = Math.max(0, Math.min(1, Number(t) || 0));283
return Math.round(t * n);284
};@@ -0,0 +1,137 @@
1
'use strict';
2
3
const { describe, it } = require('node:test');
4
const assert = require('node:assert/strict');
5
const { spawnSync } = require('node:child_process');
6
const path = require('node:path');
7
8
const GUARD = path.join(__dirname, '..', 'ci', 'deploy_guard.py');
9
10
function run (env)
11
{
12
return spawnSync('python3', [GUARD], {
13
env: { ...process.env, ...env },
14
encoding: 'utf8'
15
});
16
}
17
18
function projectDir (env)
19
{
20
const py = [
21
'import os,sys',
22
'sys.path.insert(0, "ci")',
23
'from deploy_guard import project_dir',
24
'print(project_dir(os.environ))'
25
].join('; ');
26
return spawnSync('python3', ['-c', py], {
27
cwd: path.join(__dirname, '..'),
28
env: { ...process.env, ...env },
29
encoding: 'utf8'
30
});
31
}
32
33
describe('deploy_guard', () =>
34
{
35
it('expands $timftproot and ${timftproot} and collapses double slashes', () =>
36
{
37
let r = projectDir({ timftproot: '/var/www/', projectftp: '$timftproot/allianties' });
38
assert.equal(r.status, 0, r.stderr);
39
assert.equal(r.stdout.trim(), '/var/www/allianties');
40
41
r = projectDir({ timftproot: '/var/www', projectftp: '${timftproot}/allianties' });
42
assert.equal(r.status, 0, r.stderr);
43
assert.equal(r.stdout.trim(), '/var/www/allianties');
44
45
r = projectDir({ timftproot: '/var/www/', projectftp: '${timftproot}/allianties' });
46
assert.equal(r.status, 0, r.stderr);
47
assert.equal(r.stdout.trim(), '/var/www/allianties');
48
});
49
50
it('refuses the FTP root, a missing secret, and a non-allianties leaf', () =>
51
{
52
let r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot' });
53
assert.notEqual(r.status, 0);
54
assert.match(r.stderr, /GEBLOKKEERD/);
55
56
r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot/other' });
57
assert.notEqual(r.status, 0);
58
assert.match(r.stderr, /allianties/);
59
60
r = projectDir({ timftproot: '/var/www' });
61
assert.notEqual(r.status, 0);
62
});
63
64
it('the CLI exits 0 for a good path and does not print the path', () =>
65
{
66
const r = run({ timftproot: '/var/www', projectftp: '$timftproot/allianties' });
67
assert.equal(r.status, 0, r.stderr);
68
assert.match(r.stdout, /ok/i);
69
assert.doesNotMatch(r.stdout + r.stderr, /\/var\/www/);
70
});
71
});
72
73
describe('assert_safe_target', () =>
74
{
75
it('allows a new, empty, previous, or leftover-files folder and only logs foreign names', () =>
76
{
77
const py = [
78
'import sys',
79
'sys.path.insert(0, "ci")',
80
'from deploy import assert_safe_target, deploy_commands',
81
'assert_safe_target(False, [])',
82
'assert_safe_target(True, [])',
83
'assert_safe_target(True, ["index.html", "game.js", "framework.js", "style.css", "images"])',
84
// Leftovers, including a host favicon, must not abort.
85
'assert_safe_target(True, ["favicon.ico", "index.php", "notes.txt"])',
86
'print("safe-target ok")'
87
].join('\n');
88
const r = spawnSync('python3', ['-c', py], {
89
cwd: path.join(__dirname, '..'),
90
encoding: 'utf8'
91
});
92
assert.equal(r.status, 0, r.stdout + r.stderr);
93
assert.match(r.stdout, /safe-target ok/);
94
assert.match(r.stdout, /favicon\.ico blijft ongemoeid/);
95
assert.match(r.stdout, /index\.php/);
96
assert.doesNotMatch(r.stdout + r.stderr, /GEBLOKKEERD/);
97
});
98
99
it('the FTP mirror never deletes, never uploads favicon.ico, and leaves data/ alone', () =>
100
{
101
const py = [
102
'import sys',
103
'sys.path.insert(0, "ci")',
104
'from pathlib import Path',
105
'from deploy import deploy_commands',
106
'env = {"timftphost": "ftp://example.test", "timftpuser": "u", "timftppassword": "p"}',
107
'cmds = "\\n".join(deploy_commands(env, "/var/www/allianties", Path("build")))',
108
'assert "--delete" not in cmds, cmds',
109
'assert "--exclude-glob \\"favicon.ico\\"" in cmds, cmds',
110
'assert "--exclude-glob \\"data/**\\"" in cmds, cmds',
111
'assert "--exclude-glob \\"**/config.php\\"" in cmds, cmds',
112
'assert "data/.htaccess" in cmds, cmds',
113
'assert "put " in cmds, cmds',
114
'print("mirror ok")'
115
].join('\n');
116
const r = spawnSync('python3', ['-c', py], {
117
cwd: path.join(__dirname, '..'),
118
encoding: 'utf8'
119
});
120
assert.equal(r.status, 0, r.stdout + r.stderr);
121
assert.match(r.stdout, /mirror ok/);
122
});
123
});
124
125
126
describe('auth_config_php', () =>
127
{
128
it('is covered by ci/test_deploy_auth.py (PHP escaping, empty secret, no leak in lftp)', () =>
129
{
130
const r = spawnSync('python3', ['ci/test_deploy_auth.py'], {
131
cwd: path.join(__dirname, '..'),
132
encoding: 'utf8'
133
});
134
assert.equal(r.status, 0, r.stdout + r.stderr);
135
assert.match(r.stdout, /ok/);
136
});
137
});
@@ -0,0 +1,137 @@1
'use strict';2
3
const { describe, it } = require('node:test');4
const assert = require('node:assert/strict');5
const { spawnSync } = require('node:child_process');6
const path = require('node:path');7
8
const GUARD = path.join(__dirname, '..', 'ci', 'deploy_guard.py');9
10
function run (env)11
{12
return spawnSync('python3', [GUARD], {13
env: { ...process.env, ...env },14
encoding: 'utf8'15
});16
}17
18
function projectDir (env)19
{20
const py = [21
'import os,sys',22
'sys.path.insert(0, "ci")',23
'from deploy_guard import project_dir',24
'print(project_dir(os.environ))'25
].join('; ');26
return spawnSync('python3', ['-c', py], {27
cwd: path.join(__dirname, '..'),28
env: { ...process.env, ...env },29
encoding: 'utf8'30
});31
}32
33
describe('deploy_guard', () =>34
{35
it('expands $timftproot and ${timftproot} and collapses double slashes', () =>36
{37
let r = projectDir({ timftproot: '/var/www/', projectftp: '$timftproot/allianties' });38
assert.equal(r.status, 0, r.stderr);39
assert.equal(r.stdout.trim(), '/var/www/allianties');40
41
r = projectDir({ timftproot: '/var/www', projectftp: '${timftproot}/allianties' });42
assert.equal(r.status, 0, r.stderr);43
assert.equal(r.stdout.trim(), '/var/www/allianties');44
45
r = projectDir({ timftproot: '/var/www/', projectftp: '${timftproot}/allianties' });46
assert.equal(r.status, 0, r.stderr);47
assert.equal(r.stdout.trim(), '/var/www/allianties');48
});49
50
it('refuses the FTP root, a missing secret, and a non-allianties leaf', () =>51
{52
let r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot' });53
assert.notEqual(r.status, 0);54
assert.match(r.stderr, /GEBLOKKEERD/);55
56
r = projectDir({ timftproot: '/var/www', projectftp: '$timftproot/other' });57
assert.notEqual(r.status, 0);58
assert.match(r.stderr, /allianties/);59
60
r = projectDir({ timftproot: '/var/www' });61
assert.notEqual(r.status, 0);62
});63
64
it('the CLI exits 0 for a good path and does not print the path', () =>65
{66
const r = run({ timftproot: '/var/www', projectftp: '$timftproot/allianties' });67
assert.equal(r.status, 0, r.stderr);68
assert.match(r.stdout, /ok/i);69
assert.doesNotMatch(r.stdout + r.stderr, /\/var\/www/);70
});71
});72
73
describe('assert_safe_target', () =>74
{75
it('allows a new, empty, previous, or leftover-files folder and only logs foreign names', () =>76
{77
const py = [78
'import sys',79
'sys.path.insert(0, "ci")',80
'from deploy import assert_safe_target, deploy_commands',81
'assert_safe_target(False, [])',82
'assert_safe_target(True, [])',83
'assert_safe_target(True, ["index.html", "game.js", "framework.js", "style.css", "images"])',84
// Leftovers, including a host favicon, must not abort.85
'assert_safe_target(True, ["favicon.ico", "index.php", "notes.txt"])',86
'print("safe-target ok")'87
].join('\n');88
const r = spawnSync('python3', ['-c', py], {89
cwd: path.join(__dirname, '..'),90
encoding: 'utf8'91
});92
assert.equal(r.status, 0, r.stdout + r.stderr);93
assert.match(r.stdout, /safe-target ok/);94
assert.match(r.stdout, /favicon\.ico blijft ongemoeid/);95
assert.match(r.stdout, /index\.php/);96
assert.doesNotMatch(r.stdout + r.stderr, /GEBLOKKEERD/);97
});98
99
it('the FTP mirror never deletes, never uploads favicon.ico, and leaves data/ alone', () =>100
{101
const py = [102
'import sys',103
'sys.path.insert(0, "ci")',104
'from pathlib import Path',105
'from deploy import deploy_commands',106
'env = {"timftphost": "ftp://example.test", "timftpuser": "u", "timftppassword": "p"}',107
'cmds = "\\n".join(deploy_commands(env, "/var/www/allianties", Path("build")))',108
'assert "--delete" not in cmds, cmds',109
'assert "--exclude-glob \\"favicon.ico\\"" in cmds, cmds',110
'assert "--exclude-glob \\"data/**\\"" in cmds, cmds',111
'assert "--exclude-glob \\"**/config.php\\"" in cmds, cmds',112
'assert "data/.htaccess" in cmds, cmds',113
'assert "put " in cmds, cmds',114
'print("mirror ok")'115
].join('\n');116
const r = spawnSync('python3', ['-c', py], {117
cwd: path.join(__dirname, '..'),118
encoding: 'utf8'119
});120
assert.equal(r.status, 0, r.stdout + r.stderr);121
assert.match(r.stdout, /mirror ok/);122
});123
});124
125
126
describe('auth_config_php', () =>127
{128
it('is covered by ci/test_deploy_auth.py (PHP escaping, empty secret, no leak in lftp)', () =>129
{130
const r = spawnSync('python3', ['ci/test_deploy_auth.py'], {131
cwd: path.join(__dirname, '..'),132
encoding: 'utf8'133
});134
assert.equal(r.status, 0, r.stdout + r.stderr);135
assert.match(r.stdout, /ok/);136
});137
});@@ -0,0 +1,77 @@
1
'use strict';
2
const { describe, it } = require('node:test');
3
const assert = require('node:assert/strict');
4
const catalog = require('../server/lib/i18n.json');
5
const I18n = require('../src/i18n.js');
6
7
const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
8
9
describe('i18n catalog', () =>
10
{
11
it('lists every supported locale', () =>
12
{
13
assert.deepEqual(catalog.localeIds, LOCALES);
14
for (const loc of LOCALES)
15
{ assert.ok(catalog.locales[loc], loc); }
16
assert.equal(I18n.LOCALES.length, 10);
17
assert.equal(I18n.DEFAULT, 'en');
18
});
19
20
it('has the same non-empty keys in every language', () =>
21
{
22
const enKeys = Object.keys(catalog.locales.en).sort();
23
assert.ok(enKeys.length > 80, 'enough strings: ' + enKeys.length);
24
for (const loc of LOCALES)
25
{
26
const keys = Object.keys(catalog.locales[loc]).sort();
27
assert.deepEqual(keys, enKeys, loc + ' keys differ from English');
28
for (const k of keys)
29
{
30
const v = catalog.locales[loc][k];
31
assert.equal(typeof v, 'string', loc + ' ' + k);
32
assert.ok(v.length > 0, 'empty ' + loc + ' ' + k);
33
}
34
}
35
});
36
37
it('keeps English placeholders in every translation', () =>
38
{
39
const ph = /\{(\w+)\}/g;
40
const en = catalog.locales.en;
41
for (const loc of LOCALES)
42
{
43
if (loc === 'en') { continue; }
44
for (const [k, ev] of Object.entries(en))
45
{
46
if (k.endsWith('Html')) { continue; }
47
const enPh = new Set((ev.match(ph) || []).sort());
48
const locPh = new Set((catalog.locales[loc][k].match(ph) || []).sort());
49
assert.deepEqual([...locPh].sort(), [...enPh].sort(), k + ' in ' + loc);
50
}
51
}
52
});
53
54
it('never translates the game name Allianties', () =>
55
{
56
for (const loc of LOCALES)
57
{
58
assert.equal(catalog.locales[loc]['app.name'], 'Allianties', loc);
59
assert.match(catalog.locales[loc]['auth.backToGame'], /Allianties/);
60
}
61
});
62
63
it('maps every known server error code', () =>
64
{
65
const codes = [
66
'login','csrf','not_host','min_players','not_in_game','dead','no_ap',
67
'occupied','impassable','out_of_range','invalid_move','game_started',
68
'game_finished','lobby_full','unknown_code','cannot_vote','bad_vote',
69
'bad_give','unknown_action','ceasefire','generic'
70
];
71
for (const c of codes)
72
{
73
assert.equal(catalog.errors[c], 'error.' + c, c);
74
assert.ok(catalog.locales.en['error.' + c], 'en missing error.' + c);
75
}
76
});
77
});
@@ -0,0 +1,77 @@1
'use strict';2
const { describe, it } = require('node:test');3
const assert = require('node:assert/strict');4
const catalog = require('../server/lib/i18n.json');5
const I18n = require('../src/i18n.js');6
7
const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];8
9
describe('i18n catalog', () =>10
{11
it('lists every supported locale', () =>12
{13
assert.deepEqual(catalog.localeIds, LOCALES);14
for (const loc of LOCALES)15
{ assert.ok(catalog.locales[loc], loc); }16
assert.equal(I18n.LOCALES.length, 10);17
assert.equal(I18n.DEFAULT, 'en');18
});19
20
it('has the same non-empty keys in every language', () =>21
{22
const enKeys = Object.keys(catalog.locales.en).sort();23
assert.ok(enKeys.length > 80, 'enough strings: ' + enKeys.length);24
for (const loc of LOCALES)25
{26
const keys = Object.keys(catalog.locales[loc]).sort();27
assert.deepEqual(keys, enKeys, loc + ' keys differ from English');28
for (const k of keys)29
{30
const v = catalog.locales[loc][k];31
assert.equal(typeof v, 'string', loc + ' ' + k);32
assert.ok(v.length > 0, 'empty ' + loc + ' ' + k);33
}34
}35
});36
37
it('keeps English placeholders in every translation', () =>38
{39
const ph = /\{(\w+)\}/g;40
const en = catalog.locales.en;41
for (const loc of LOCALES)42
{43
if (loc === 'en') { continue; }44
for (const [k, ev] of Object.entries(en))45
{46
if (k.endsWith('Html')) { continue; }47
const enPh = new Set((ev.match(ph) || []).sort());48
const locPh = new Set((catalog.locales[loc][k].match(ph) || []).sort());49
assert.deepEqual([...locPh].sort(), [...enPh].sort(), k + ' in ' + loc);50
}51
}52
});53
54
it('never translates the game name Allianties', () =>55
{56
for (const loc of LOCALES)57
{58
assert.equal(catalog.locales[loc]['app.name'], 'Allianties', loc);59
assert.match(catalog.locales[loc]['auth.backToGame'], /Allianties/);60
}61
});62
63
it('maps every known server error code', () =>64
{65
const codes = [66
'login','csrf','not_host','min_players','not_in_game','dead','no_ap',67
'occupied','impassable','out_of_range','invalid_move','game_started',68
'game_finished','lobby_full','unknown_code','cannot_vote','bad_vote',69
'bad_give','unknown_action','ceasefire','generic'70
];71
for (const c of codes)72
{73
assert.equal(catalog.errors[c], 'error.' + c, c);74
assert.ok(catalog.locales.en['error.' + c], 'en missing error.' + c);75
}76
});77
});@@ -0,0 +1,145 @@
1
'use strict';
2
const { describe, it } = require('node:test');
3
const assert = require('node:assert/strict');
4
const Rules = require('../src/rules.js');
5
6
function ams(iso) {
7
// iso like '2026-11-13 23:30:00' as Europe/Amsterdam wall clock → unix
8
const [d, t] = iso.split(' ');
9
const hm = t.slice(0, 5);
10
const sec = parseInt(t.slice(6), 10) || 0;
11
return Rules.amsterdamWallclock(d, hm) + sec;
12
}
13
14
describe('Rules grid and Chebyshev', () => {
15
it('scales the board with player count', () => {
16
assert.equal(Rules.gridSize(2), 6);
17
assert.equal(Rules.gridSize(4), 6);
18
assert.equal(Rules.gridSize(8), 7);
19
assert.equal(Rules.gridSize(12), 9);
20
assert.equal(Rules.maxInset(6), 1);
21
assert.equal(Rules.maxInset(7), 2);
22
});
23
it('uses Chebyshev distance (diagonals included)', () => {
24
assert.equal(Rules.chebyshev(0, 0, 2, 2), 2);
25
assert.equal(Rules.chebyshev(0, 0, 2, 0), 2);
26
});
27
it('passable accounts for arena inset', () => {
28
assert.equal(Rules.isPassable(6, 1, 0, 0), false);
29
assert.equal(Rules.isPassable(6, 1, 1, 1), true);
30
assert.equal(Rules.isPassable(6, 1, 5, 3), false);
31
});
32
});
33
34
describe('Rules cease-fire, midnight wrap and DST', () => {
35
const rules = {
36
ceasefire: true,
37
ceasefire_ranges: [
38
{ start: '22:00', end: '06:00' },
39
{ start: '12:00', end: '13:00' }
40
]
41
};
42
43
it('treats 23:30 as cease-fire wrapping to 06:00 next day', () => {
44
const info = Rules.ceasefireInfo(rules, ams('2026-11-13 23:30:00'));
45
assert.ok(info && info.active);
46
assert.equal(info.until, ams('2026-11-14 06:00:00'));
47
});
48
49
it('treats the end timestamp as exclusive', () => {
50
const info = Rules.ceasefireInfo(rules, ams('2026-11-14 06:00:00'));
51
assert.equal(info.active, false);
52
assert.equal(info.until, ams('2026-11-14 12:00:00'));
53
});
54
55
it('handles a second daytime range and countdown seconds', () => {
56
const info = Rules.ceasefireInfo(rules, ams('2026-11-14 12:30:00'));
57
assert.equal(info.active, true);
58
assert.equal(info.until, ams('2026-11-14 13:00:00'));
59
const before = Rules.ceasefireInfo(rules, ams('2026-11-14 21:59:00'));
60
assert.equal(before.active, false);
61
assert.equal(before.seconds, 60);
62
const late = Rules.ceasefireInfo(rules, ams('2026-11-15 05:59:00'));
63
assert.equal(late.active, true);
64
assert.equal(late.seconds, 60);
65
});
66
67
it('shortens 01:00–04:00 across the 2026 spring-forward to 2 real hours', () => {
68
const r = { ceasefire: true, ceasefire_ranges: [{ start: '01:00', end: '04:00' }] };
69
const start = ams('2026-03-29 01:00:00');
70
const info = Rules.ceasefireInfo(r, start);
71
assert.equal(info.active, true);
72
assert.equal(info.until - start, 2 * 3600);
73
const three = Rules.ceasefireInfo(r, ams('2026-03-29 03:00:00'));
74
assert.equal(three.active, true);
75
assert.equal(three.seconds, 3600);
76
const half = Rules.ceasefireInfo(r, ams('2026-03-29 00:30:00'));
77
assert.equal(half.active, false);
78
assert.equal(half.seconds, 1800);
79
});
80
81
it('lengthens 01:00–03:30 across the 2026 fall-back to 3.5 real hours', () => {
82
const r = { ceasefire: true, ceasefire_ranges: [{ start: '01:00', end: '03:30' }] };
83
const start = ams('2026-10-25 01:00:00');
84
const info = Rules.ceasefireInfo(r, start);
85
assert.equal(info.active, true);
86
assert.equal(info.until - start, 3.5 * 3600);
87
// Both occurrences of 02:15 are inside.
88
const first = Rules.ceasefireInfo(r, start + 75 * 60);
89
const second = Rules.ceasefireInfo(r, start + (75 + 60) * 60);
90
assert.equal(first.active, true);
91
assert.equal(second.active, true);
92
const after = Rules.ceasefireInfo(r, ams('2026-10-25 03:30:00'));
93
assert.equal(after.active, false);
94
});
95
96
it('is inactive when the rule is off or ranges are empty', () => {
97
assert.equal(Rules.ceasefireInfo({ ceasefire: false, ceasefire_ranges: [{ start: '00:00', end: '23:59' }] }, ams('2026-11-14 12:00:00')), null);
98
assert.equal(Rules.ceasefireInfo({ ceasefire: true, ceasefire_ranges: [] }, ams('2026-11-14 12:00:00')), null);
99
});
100
101
it('merges overlapping ranges for the countdown', () => {
102
const r = { ceasefire: true, ceasefire_ranges: [
103
{ start: '10:00', end: '12:00' },
104
{ start: '11:00', end: '13:00' }
105
] };
106
const info = Rules.ceasefireInfo(r, ams('2026-11-14 10:30:00'));
107
assert.equal(info.active, true);
108
assert.equal(info.until, ams('2026-11-14 13:00:00'));
109
});
110
111
it('formats HH:MM:SS countdowns', () => {
112
assert.equal(Rules.formatHms(0), '00:00:00');
113
assert.equal(Rules.formatHms(5), '00:00:05');
114
assert.equal(Rules.formatHms(3661), '01:01:01');
115
assert.equal(Rules.formatHms(12 * 3600 + 34 * 60 + 56), '12:34:56');
116
});
117
});
118
119
describe('Rules timelineIndex (nearest event)', () =>
120
{
121
it('returns 0 when there are no spends', () =>
122
{
123
assert.equal(Rules.timelineIndex(0.9, 0), 0);
124
assert.equal(Rules.timelineIndex(0, 0), 0);
125
});
126
it('maps 0 to the start and 1 to live (after the last spend)', () =>
127
{
128
assert.equal(Rules.timelineIndex(0, 4), 0);
129
assert.equal(Rules.timelineIndex(1, 4), 4);
130
assert.equal(Rules.timelineIndex(0, 1), 0);
131
assert.equal(Rules.timelineIndex(1, 1), 1);
132
});
133
it('jumps to the nearest event along the bar', () =>
134
{
135
// 4 spends: slots at 0, 0.25, 0.5, 0.75, 1
136
assert.equal(Rules.timelineIndex(0.12, 4), 0);
137
assert.equal(Rules.timelineIndex(0.13, 4), 1);
138
assert.equal(Rules.timelineIndex(0.26, 4), 1);
139
assert.equal(Rules.timelineIndex(0.37, 4), 1);
140
assert.equal(Rules.timelineIndex(0.38, 4), 2);
141
assert.equal(Rules.timelineIndex(0.88, 4), 4);
142
assert.equal(Rules.timelineIndex(1.5, 4), 4);
143
assert.equal(Rules.timelineIndex(-0.2, 4), 0);
144
});
145
});
@@ -0,0 +1,145 @@1
'use strict';2
const { describe, it } = require('node:test');3
const assert = require('node:assert/strict');4
const Rules = require('../src/rules.js');5
6
function ams(iso) {7
// iso like '2026-11-13 23:30:00' as Europe/Amsterdam wall clock → unix8
const [d, t] = iso.split(' ');9
const hm = t.slice(0, 5);10
const sec = parseInt(t.slice(6), 10) || 0;11
return Rules.amsterdamWallclock(d, hm) + sec;12
}13
14
describe('Rules grid and Chebyshev', () => {15
it('scales the board with player count', () => {16
assert.equal(Rules.gridSize(2), 6);17
assert.equal(Rules.gridSize(4), 6);18
assert.equal(Rules.gridSize(8), 7);19
assert.equal(Rules.gridSize(12), 9);20
assert.equal(Rules.maxInset(6), 1);21
assert.equal(Rules.maxInset(7), 2);22
});23
it('uses Chebyshev distance (diagonals included)', () => {24
assert.equal(Rules.chebyshev(0, 0, 2, 2), 2);25
assert.equal(Rules.chebyshev(0, 0, 2, 0), 2);26
});27
it('passable accounts for arena inset', () => {28
assert.equal(Rules.isPassable(6, 1, 0, 0), false);29
assert.equal(Rules.isPassable(6, 1, 1, 1), true);30
assert.equal(Rules.isPassable(6, 1, 5, 3), false);31
});32
});33
34
describe('Rules cease-fire, midnight wrap and DST', () => {35
const rules = {36
ceasefire: true,37
ceasefire_ranges: [38
{ start: '22:00', end: '06:00' },39
{ start: '12:00', end: '13:00' }40
]41
};42
43
it('treats 23:30 as cease-fire wrapping to 06:00 next day', () => {44
const info = Rules.ceasefireInfo(rules, ams('2026-11-13 23:30:00'));45
assert.ok(info && info.active);46
assert.equal(info.until, ams('2026-11-14 06:00:00'));47
});48
49
it('treats the end timestamp as exclusive', () => {50
const info = Rules.ceasefireInfo(rules, ams('2026-11-14 06:00:00'));51
assert.equal(info.active, false);52
assert.equal(info.until, ams('2026-11-14 12:00:00'));53
});54
55
it('handles a second daytime range and countdown seconds', () => {56
const info = Rules.ceasefireInfo(rules, ams('2026-11-14 12:30:00'));57
assert.equal(info.active, true);58
assert.equal(info.until, ams('2026-11-14 13:00:00'));59
const before = Rules.ceasefireInfo(rules, ams('2026-11-14 21:59:00'));60
assert.equal(before.active, false);61
assert.equal(before.seconds, 60);62
const late = Rules.ceasefireInfo(rules, ams('2026-11-15 05:59:00'));63
assert.equal(late.active, true);64
assert.equal(late.seconds, 60);65
});66
67
it('shortens 01:00–04:00 across the 2026 spring-forward to 2 real hours', () => {68
const r = { ceasefire: true, ceasefire_ranges: [{ start: '01:00', end: '04:00' }] };69
const start = ams('2026-03-29 01:00:00');70
const info = Rules.ceasefireInfo(r, start);71
assert.equal(info.active, true);72
assert.equal(info.until - start, 2 * 3600);73
const three = Rules.ceasefireInfo(r, ams('2026-03-29 03:00:00'));74
assert.equal(three.active, true);75
assert.equal(three.seconds, 3600);76
const half = Rules.ceasefireInfo(r, ams('2026-03-29 00:30:00'));77
assert.equal(half.active, false);78
assert.equal(half.seconds, 1800);79
});80
81
it('lengthens 01:00–03:30 across the 2026 fall-back to 3.5 real hours', () => {82
const r = { ceasefire: true, ceasefire_ranges: [{ start: '01:00', end: '03:30' }] };83
const start = ams('2026-10-25 01:00:00');84
const info = Rules.ceasefireInfo(r, start);85
assert.equal(info.active, true);86
assert.equal(info.until - start, 3.5 * 3600);87
// Both occurrences of 02:15 are inside.88
const first = Rules.ceasefireInfo(r, start + 75 * 60);89
const second = Rules.ceasefireInfo(r, start + (75 + 60) * 60);90
assert.equal(first.active, true);91
assert.equal(second.active, true);92
const after = Rules.ceasefireInfo(r, ams('2026-10-25 03:30:00'));93
assert.equal(after.active, false);94
});95
96
it('is inactive when the rule is off or ranges are empty', () => {97
assert.equal(Rules.ceasefireInfo({ ceasefire: false, ceasefire_ranges: [{ start: '00:00', end: '23:59' }] }, ams('2026-11-14 12:00:00')), null);98
assert.equal(Rules.ceasefireInfo({ ceasefire: true, ceasefire_ranges: [] }, ams('2026-11-14 12:00:00')), null);99
});100
101
it('merges overlapping ranges for the countdown', () => {102
const r = { ceasefire: true, ceasefire_ranges: [103
{ start: '10:00', end: '12:00' },104
{ start: '11:00', end: '13:00' }105
] };106
const info = Rules.ceasefireInfo(r, ams('2026-11-14 10:30:00'));107
assert.equal(info.active, true);108
assert.equal(info.until, ams('2026-11-14 13:00:00'));109
});110
111
it('formats HH:MM:SS countdowns', () => {112
assert.equal(Rules.formatHms(0), '00:00:00');113
assert.equal(Rules.formatHms(5), '00:00:05');114
assert.equal(Rules.formatHms(3661), '01:01:01');115
assert.equal(Rules.formatHms(12 * 3600 + 34 * 60 + 56), '12:34:56');116
});117
});118
119
describe('Rules timelineIndex (nearest event)', () =>120
{121
it('returns 0 when there are no spends', () =>122
{123
assert.equal(Rules.timelineIndex(0.9, 0), 0);124
assert.equal(Rules.timelineIndex(0, 0), 0);125
});126
it('maps 0 to the start and 1 to live (after the last spend)', () =>127
{128
assert.equal(Rules.timelineIndex(0, 4), 0);129
assert.equal(Rules.timelineIndex(1, 4), 4);130
assert.equal(Rules.timelineIndex(0, 1), 0);131
assert.equal(Rules.timelineIndex(1, 1), 1);132
});133
it('jumps to the nearest event along the bar', () =>134
{135
// 4 spends: slots at 0, 0.25, 0.5, 0.75, 1136
assert.equal(Rules.timelineIndex(0.12, 4), 0);137
assert.equal(Rules.timelineIndex(0.13, 4), 1);138
assert.equal(Rules.timelineIndex(0.26, 4), 1);139
assert.equal(Rules.timelineIndex(0.37, 4), 1);140
assert.equal(Rules.timelineIndex(0.38, 4), 2);141
assert.equal(Rules.timelineIndex(0.88, 4), 4);142
assert.equal(Rules.timelineIndex(1.5, 4), 4);143
assert.equal(Rules.timelineIndex(-0.2, 4), 0);144
});145
});@@ -0,0 +1,331 @@
1
#!/usr/bin/env python3
2
"""Desktop + mobile screenshots and a two-player local flow."""
3
from __future__ import annotations
4
5
import sys
6
from pathlib import Path
7
from urllib.parse import quote
8
9
from playwright.sync_api import sync_playwright, expect
10
11
SHOTS = Path('/workspace/allianties-shots')
12
SHOTS.mkdir(parents=True, exist_ok=True)
13
BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://127.0.0.1:8080'
14
15
16
def shot(page, name, full=False):
17
path = SHOTS / f'{name}.png'
18
page.screenshot(path=str(path), full_page=full)
19
print('shot', path)
20
21
22
def shot_full(page, name):
23
shot(page, name, full=True)
24
25
26
def main():
27
with sync_playwright() as p:
28
browser = p.chromium.launch(headless=True)
29
desk = browser.new_context(viewport={'width': 1280, 'height': 800}, locale='en-GB')
30
page = desk.new_page()
31
page.goto(BASE + '/', wait_until='networkidle')
32
page.wait_for_selector('#menu h1')
33
expect(page.locator('#menu h1')).to_have_text('Allianties')
34
shot_full(page, 'desktop-menu-guest')
35
36
# Flag picker
37
page.locator('#lang-current').click()
38
page.wait_for_selector('#lang-list:not([hidden])')
39
shot(page, 'desktop-lang-picker')
40
page.locator('#lang-current').click() # close, stay in English
41
page.wait_for_timeout(200)
42
43
# Login test user 1
44
page.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
45
page.wait_for_selector('#btn-create')
46
shot_full(page, 'desktop-menu-loggedin')
47
48
page.locator('#btn-create').click()
49
page.wait_for_selector('#lobby:not([hidden])')
50
page.wait_for_timeout(200)
51
shot_full(page, 'desktop-lobby')
52
53
# Enable shrink, AP loot, cease-fire, set AP time, show clock + vis options
54
page.locator('#rule-shrink').check()
55
page.locator('#rule-ap-loot').check()
56
page.locator('#rule-ap-time').fill('00:00')
57
page.locator('#rule-ceasefire').check()
58
page.wait_for_selector('#ceasefire-editor:not([hidden])')
59
page.wait_for_timeout(200)
60
shot_full(page, 'desktop-lobby-rules-clock')
61
62
page.locator('#cf-add').click()
63
page.wait_for_timeout(300)
64
# Use a daytime range so we can still shoot later (not wrapping current night)
65
# Fill via evaluate so locale 12h inputs don't bite.
66
page.evaluate("""() => {
67
const inputs = document.querySelectorAll('#cf-ranges input[type=time]');
68
if (inputs[0]) inputs[0].value = '10:00';
69
if (inputs[1]) inputs[1].value = '12:00';
70
inputs[0] && inputs[0].dispatchEvent(new Event('change', { bubbles: true }));
71
}""")
72
page.wait_for_timeout(400)
73
shot_full(page, 'desktop-lobby-cf-range')
74
shot_full(page, 'desktop-lobby-options') # time picker, loot, vis, clock
75
76
# Scroll visibility into view
77
vis = page.locator('#lobby-visibility')
78
if vis.count():
79
vis.scroll_into_view_if_needed()
80
page.wait_for_timeout(150)
81
shot(page, 'desktop-lobby-visibility')
82
83
code = page.locator('#lobby-code').inner_text().strip()
84
print('lobby code', code)
85
86
# Turn cease-fire OFF before start so shots are legal; keep the other options.
87
# (Clock already screenshotted.) 10:00-12:00 is already off at night, fine.
88
89
desk2 = browser.new_context(viewport={'width': 1280, 'height': 800}, locale='en-GB')
90
page2 = desk2.new_page()
91
next_url = quote('index.html?join=' + code, safe='')
92
page2.goto(BASE + '/auth.php?test=2&next=' + next_url, wait_until='networkidle')
93
print('player2 url', page2.url)
94
try:
95
page2.wait_for_selector('#lobby:not([hidden]), #game:not([hidden])', timeout=15000)
96
except Exception:
97
shot(page2, 'debug-player2')
98
print('player2 text', page2.locator('body').inner_text()[:800])
99
raise
100
page2.wait_for_timeout(300)
101
shot_full(page2, 'desktop-player2-lobby')
102
103
page.wait_for_function(
104
"() => document.querySelectorAll('#lobby-players li').length >= 2",
105
timeout=15000,
106
)
107
shot_full(page, 'desktop-lobby-two-players')
108
page.locator('#btn-start').click()
109
page.wait_for_selector('#game:not([hidden])')
110
page.wait_for_timeout(400)
111
expect(page.locator('#ap-hms')).to_be_visible()
112
shot(page, 'desktop-game')
113
114
# Click own tank, screenshot selection + move targets + timeline controls
115
pieces = page.locator('#board .cell:has(.piece, .piece-initials)')
116
print('pieces', pieces.count())
117
if pieces.count() >= 1:
118
pieces.nth(0).click()
119
page.wait_for_timeout(250)
120
shot(page, 'desktop-game-selected')
121
# Move toward the other player if a move-target exists
122
targets = page.locator('#board .cell.move-target')
123
if targets.count() >= 1:
124
# Prefer a cell closer to the bottom (higher y) — downward toward P2
125
targets.last.click()
126
page.wait_for_timeout(500)
127
shot(page, 'desktop-game-moved')
128
129
# Player 2: after poll, should see the move; in range now, can give / attack
130
page2.wait_for_timeout(3500)
131
# If still lobby, start already happened — poll should switch to game
132
if page2.locator('#lobby:not([hidden])').count():
133
page2.wait_for_selector('#game:not([hidden])', timeout=10000)
134
page2.wait_for_selector('#game:not([hidden])', timeout=10000)
135
page2.wait_for_timeout(300)
136
shot(page2, 'desktop-game-p2')
137
138
# Click the opponent (T1, first or the non-own piece)
139
def click_opponent(pg):
140
cells = pg.locator('#board .cell:has(.piece, .piece-initials)')
141
n = cells.count()
142
# Click each until the sheet opens
143
for i in range(n):
144
cells.nth(i).click()
145
pg.wait_for_timeout(200)
146
if pg.locator('#sheet:not([hidden])').count():
147
return True
148
return False
149
150
if click_opponent(page2):
151
shot(page2, 'desktop-player-menu')
152
# Info
153
page2.locator('#sheet-body button').first.click()
154
page2.wait_for_selector('#modal:not([hidden])')
155
page2.wait_for_timeout(200)
156
shot(page2, 'desktop-info')
157
page2.locator('#modal-close').click()
158
page2.wait_for_timeout(150)
159
160
if click_opponent(page2):
161
# Give AP — the Give button is usually 3rd (Info, Attack, Give, Message)
162
btns = page2.locator('#sheet-body button')
163
give = None
164
for i in range(btns.count()):
165
t = btns.nth(i).inner_text()
166
if 'Give' in t or 'geven' in t.lower() or 'AP' in t:
167
give = btns.nth(i)
168
break
169
if give is None and btns.count() >= 3:
170
give = btns.nth(2)
171
if give is not None:
172
give.click()
173
page2.wait_for_selector('#modal:not([hidden])')
174
page2.wait_for_timeout(200)
175
shot(page2, 'desktop-give-ap')
176
# Actually send 1 AP so we get a green arrow in playback
177
send = page2.locator('#modal-body button').last
178
if not send.is_disabled():
179
send.click()
180
page2.wait_for_timeout(600)
181
else:
182
page2.locator('#modal-close').click()
183
184
# Chat
185
if click_opponent(page2):
186
btns = page2.locator('#sheet-body button')
187
chat = None
188
for i in range(btns.count()):
189
t = btns.nth(i).inner_text()
190
if 'message' in t.lower() or 'bericht' in t.lower() or 'chat' in t.lower():
191
chat = btns.nth(i)
192
break
193
if chat is None and btns.count() >= 4:
194
chat = btns.nth(3)
195
if chat is not None:
196
chat.click()
197
page2.wait_for_selector('#modal:not([hidden])')
198
page2.wait_for_timeout(200)
199
# type a message
200
inp = page2.locator('#modal-body input[type="text"]')
201
if inp.count():
202
inp.fill('Good luck!')
203
shot(page2, 'desktop-chat')
204
form_btn = page2.locator('#modal-body button[type="submit"]')
205
if form_btn.count():
206
form_btn.click()
207
page2.wait_for_timeout(400)
208
shot(page2, 'desktop-chat-sent')
209
page2.locator('#modal-close').click()
210
211
# Advance a day on player 1 so they have AP again, then shoot (red arrow)
212
page.evaluate("""async () => {
213
if (window.Api && App.game) {
214
try { await Api.debugAdvance(App.game.id, 1); await App.refreshFull(); }
215
catch (e) { console.error(e); }
216
}
217
}""")
218
page.wait_for_timeout(500)
219
if click_opponent(page):
220
btns = page.locator('#sheet-body button')
221
atk = None
222
for i in range(btns.count()):
223
t = btns.nth(i).inner_text()
224
if 'Attack' in t or 'Aanval' in t or 'Shoot' in t or 'schiet' in t.lower():
225
atk = btns.nth(i)
226
break
227
if atk is None and btns.count() >= 2:
228
atk = btns.nth(1)
229
if atk is not None and not atk.is_disabled():
230
atk.click()
231
page.wait_for_timeout(500)
232
shot(page, 'desktop-game-after-shot')
233
234
# Playback arrows: rewind and play
235
if page.locator('#tl-back').count():
236
# Jump to start via stepping back many times, then play
237
for _ in range(8):
238
page.locator('#tl-back').click()
239
page.wait_for_timeout(80)
240
shot(page, 'desktop-timeline-start')
241
page.locator('#tl-play').click()
242
# Mid-playback: wait enough for a give/shoot/move arrow to show
243
page.wait_for_timeout(700)
244
shot(page, 'desktop-playback-arrows')
245
page.wait_for_timeout(900)
246
shot(page, 'desktop-playback-arrows-2')
247
# Pause, step forward, jump to present
248
if page.locator('#tl-play').get_attribute('title') and 'Pause' in (page.locator('#tl-play').get_attribute('title') or ''):
249
page.locator('#tl-play').click()
250
page.locator('#tl-fwd').click()
251
page.wait_for_timeout(200)
252
shot(page, 'desktop-timeline-step')
253
page.locator('#tl-live').click()
254
page.wait_for_timeout(200)
255
shot(page, 'desktop-timeline-live')
256
257
# Settings / surrender (don't confirm)
258
page.locator('#btn-settings').click()
259
page.wait_for_selector('#settings-panel:not([hidden])')
260
shot(page, 'desktop-settings')
261
page.locator('#btn-surrender').click()
262
page.wait_for_selector('#modal:not([hidden])')
263
shot(page, 'desktop-surrender-confirm')
264
page.locator('#modal-close').click()
265
266
# --- Mobile ---
267
mobile = browser.new_context(
268
viewport={'width': 390, 'height': 844},
269
is_mobile=True,
270
has_touch=True,
271
user_agent='Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
272
locale='en-GB',
273
)
274
mp = mobile.new_page()
275
mp.goto(BASE + '/', wait_until='networkidle')
276
shot(mp, 'mobile-menu-guest')
277
mp.locator('#lang-current').click()
278
mp.wait_for_selector('#lang-list:not([hidden])')
279
shot(mp, 'mobile-lang-picker')
280
281
mp.goto(BASE + '/auth.php?test=3', wait_until='networkidle')
282
mp.wait_for_selector('#btn-create, #menu-user')
283
shot(mp, 'mobile-menu')
284
mp.locator('#btn-create').click()
285
mp.wait_for_selector('#lobby:not([hidden])')
286
mp.locator('#rule-ceasefire').check()
287
mp.locator('#rule-ap-loot').wait_for()
288
mp.wait_for_timeout(300)
289
shot_full(mp, 'mobile-lobby-clock')
290
mp.locator('#rule-ap-time').scroll_into_view_if_needed()
291
shot(mp, 'mobile-lobby-ap-time')
292
vis = mp.locator('#lobby-visibility')
293
if vis.count():
294
vis.scroll_into_view_if_needed()
295
shot(mp, 'mobile-lobby-visibility')
296
297
# Player 2's running game on mobile
298
mobile2 = browser.new_context(
299
viewport={'width': 390, 'height': 844},
300
is_mobile=True,
301
has_touch=True,
302
locale='en-GB',
303
)
304
m2 = mobile2.new_page()
305
m2.goto(BASE + '/auth.php?test=2', wait_until='networkidle')
306
m2.wait_for_selector('#menu, #game, #lobby')
307
if m2.locator('#games-list button').count() > 0:
308
m2.locator('#games-list button').first.click()
309
m2.wait_for_selector('#game:not([hidden]), #lobby:not([hidden])')
310
m2.wait_for_timeout(400)
311
shot(m2, 'mobile-game')
312
if m2.locator('#ap-hms').count():
313
shot(m2, 'mobile-game-countdown')
314
# playback on mobile
315
if m2.locator('#tl-play').count() and m2.locator('#game:not([hidden])').count():
316
m2.locator('#tl-back').click()
317
m2.locator('#tl-back').click()
318
m2.locator('#tl-play').click()
319
m2.wait_for_timeout(700)
320
shot(m2, 'mobile-playback-arrows')
321
322
desk.close()
323
desk2.close()
324
mobile.close()
325
mobile2.close()
326
browser.close()
327
print('playwright done')
328
329
330
if __name__ == '__main__':
331
main()
@@ -0,0 +1,331 @@1
#!/usr/bin/env python32
"""Desktop + mobile screenshots and a two-player local flow."""3
from __future__ import annotations4
5
import sys6
from pathlib import Path7
from urllib.parse import quote8
9
from playwright.sync_api import sync_playwright, expect10
11
SHOTS = Path('/workspace/allianties-shots')12
SHOTS.mkdir(parents=True, exist_ok=True)13
BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://127.0.0.1:8080'14
15
16
def shot(page, name, full=False):17
path = SHOTS / f'{name}.png'18
page.screenshot(path=str(path), full_page=full)19
print('shot', path)20
21
22
def shot_full(page, name):23
shot(page, name, full=True)24
25
26
def main():27
with sync_playwright() as p:28
browser = p.chromium.launch(headless=True)29
desk = browser.new_context(viewport={'width': 1280, 'height': 800}, locale='en-GB')30
page = desk.new_page()31
page.goto(BASE + '/', wait_until='networkidle')32
page.wait_for_selector('#menu h1')33
expect(page.locator('#menu h1')).to_have_text('Allianties')34
shot_full(page, 'desktop-menu-guest')35
36
# Flag picker37
page.locator('#lang-current').click()38
page.wait_for_selector('#lang-list:not([hidden])')39
shot(page, 'desktop-lang-picker')40
page.locator('#lang-current').click() # close, stay in English41
page.wait_for_timeout(200)42
43
# Login test user 144
page.goto(BASE + '/auth.php?test=1', wait_until='networkidle')45
page.wait_for_selector('#btn-create')46
shot_full(page, 'desktop-menu-loggedin')47
48
page.locator('#btn-create').click()49
page.wait_for_selector('#lobby:not([hidden])')50
page.wait_for_timeout(200)51
shot_full(page, 'desktop-lobby')52
53
# Enable shrink, AP loot, cease-fire, set AP time, show clock + vis options54
page.locator('#rule-shrink').check()55
page.locator('#rule-ap-loot').check()56
page.locator('#rule-ap-time').fill('00:00')57
page.locator('#rule-ceasefire').check()58
page.wait_for_selector('#ceasefire-editor:not([hidden])')59
page.wait_for_timeout(200)60
shot_full(page, 'desktop-lobby-rules-clock')61
62
page.locator('#cf-add').click()63
page.wait_for_timeout(300)64
# Use a daytime range so we can still shoot later (not wrapping current night)65
# Fill via evaluate so locale 12h inputs don't bite.66
page.evaluate("""() => {67
const inputs = document.querySelectorAll('#cf-ranges input[type=time]');68
if (inputs[0]) inputs[0].value = '10:00';69
if (inputs[1]) inputs[1].value = '12:00';70
inputs[0] && inputs[0].dispatchEvent(new Event('change', { bubbles: true }));71
}""")72
page.wait_for_timeout(400)73
shot_full(page, 'desktop-lobby-cf-range')74
shot_full(page, 'desktop-lobby-options') # time picker, loot, vis, clock75
76
# Scroll visibility into view77
vis = page.locator('#lobby-visibility')78
if vis.count():79
vis.scroll_into_view_if_needed()80
page.wait_for_timeout(150)81
shot(page, 'desktop-lobby-visibility')82
83
code = page.locator('#lobby-code').inner_text().strip()84
print('lobby code', code)85
86
# Turn cease-fire OFF before start so shots are legal; keep the other options.87
# (Clock already screenshotted.) 10:00-12:00 is already off at night, fine.88
89
desk2 = browser.new_context(viewport={'width': 1280, 'height': 800}, locale='en-GB')90
page2 = desk2.new_page()91
next_url = quote('index.html?join=' + code, safe='')92
page2.goto(BASE + '/auth.php?test=2&next=' + next_url, wait_until='networkidle')93
print('player2 url', page2.url)94
try:95
page2.wait_for_selector('#lobby:not([hidden]), #game:not([hidden])', timeout=15000)96
except Exception:97
shot(page2, 'debug-player2')98
print('player2 text', page2.locator('body').inner_text()[:800])99
raise100
page2.wait_for_timeout(300)101
shot_full(page2, 'desktop-player2-lobby')102
103
page.wait_for_function(104
"() => document.querySelectorAll('#lobby-players li').length >= 2",105
timeout=15000,106
)107
shot_full(page, 'desktop-lobby-two-players')108
page.locator('#btn-start').click()109
page.wait_for_selector('#game:not([hidden])')110
page.wait_for_timeout(400)111
expect(page.locator('#ap-hms')).to_be_visible()112
shot(page, 'desktop-game')113
114
# Click own tank, screenshot selection + move targets + timeline controls115
pieces = page.locator('#board .cell:has(.piece, .piece-initials)')116
print('pieces', pieces.count())117
if pieces.count() >= 1:118
pieces.nth(0).click()119
page.wait_for_timeout(250)120
shot(page, 'desktop-game-selected')121
# Move toward the other player if a move-target exists122
targets = page.locator('#board .cell.move-target')123
if targets.count() >= 1:124
# Prefer a cell closer to the bottom (higher y) — downward toward P2125
targets.last.click()126
page.wait_for_timeout(500)127
shot(page, 'desktop-game-moved')128
129
# Player 2: after poll, should see the move; in range now, can give / attack130
page2.wait_for_timeout(3500)131
# If still lobby, start already happened — poll should switch to game132
if page2.locator('#lobby:not([hidden])').count():133
page2.wait_for_selector('#game:not([hidden])', timeout=10000)134
page2.wait_for_selector('#game:not([hidden])', timeout=10000)135
page2.wait_for_timeout(300)136
shot(page2, 'desktop-game-p2')137
138
# Click the opponent (T1, first or the non-own piece)139
def click_opponent(pg):140
cells = pg.locator('#board .cell:has(.piece, .piece-initials)')141
n = cells.count()142
# Click each until the sheet opens143
for i in range(n):144
cells.nth(i).click()145
pg.wait_for_timeout(200)146
if pg.locator('#sheet:not([hidden])').count():147
return True148
return False149
150
if click_opponent(page2):151
shot(page2, 'desktop-player-menu')152
# Info153
page2.locator('#sheet-body button').first.click()154
page2.wait_for_selector('#modal:not([hidden])')155
page2.wait_for_timeout(200)156
shot(page2, 'desktop-info')157
page2.locator('#modal-close').click()158
page2.wait_for_timeout(150)159
160
if click_opponent(page2):161
# Give AP — the Give button is usually 3rd (Info, Attack, Give, Message)162
btns = page2.locator('#sheet-body button')163
give = None164
for i in range(btns.count()):165
t = btns.nth(i).inner_text()166
if 'Give' in t or 'geven' in t.lower() or 'AP' in t:167
give = btns.nth(i)168
break169
if give is None and btns.count() >= 3:170
give = btns.nth(2)171
if give is not None:172
give.click()173
page2.wait_for_selector('#modal:not([hidden])')174
page2.wait_for_timeout(200)175
shot(page2, 'desktop-give-ap')176
# Actually send 1 AP so we get a green arrow in playback177
send = page2.locator('#modal-body button').last178
if not send.is_disabled():179
send.click()180
page2.wait_for_timeout(600)181
else:182
page2.locator('#modal-close').click()183
184
# Chat185
if click_opponent(page2):186
btns = page2.locator('#sheet-body button')187
chat = None188
for i in range(btns.count()):189
t = btns.nth(i).inner_text()190
if 'message' in t.lower() or 'bericht' in t.lower() or 'chat' in t.lower():191
chat = btns.nth(i)192
break193
if chat is None and btns.count() >= 4:194
chat = btns.nth(3)195
if chat is not None:196
chat.click()197
page2.wait_for_selector('#modal:not([hidden])')198
page2.wait_for_timeout(200)199
# type a message200
inp = page2.locator('#modal-body input[type="text"]')201
if inp.count():202
inp.fill('Good luck!')203
shot(page2, 'desktop-chat')204
form_btn = page2.locator('#modal-body button[type="submit"]')205
if form_btn.count():206
form_btn.click()207
page2.wait_for_timeout(400)208
shot(page2, 'desktop-chat-sent')209
page2.locator('#modal-close').click()210
211
# Advance a day on player 1 so they have AP again, then shoot (red arrow)212
page.evaluate("""async () => {213
if (window.Api && App.game) {214
try { await Api.debugAdvance(App.game.id, 1); await App.refreshFull(); }215
catch (e) { console.error(e); }216
}217
}""")218
page.wait_for_timeout(500)219
if click_opponent(page):220
btns = page.locator('#sheet-body button')221
atk = None222
for i in range(btns.count()):223
t = btns.nth(i).inner_text()224
if 'Attack' in t or 'Aanval' in t or 'Shoot' in t or 'schiet' in t.lower():225
atk = btns.nth(i)226
break227
if atk is None and btns.count() >= 2:228
atk = btns.nth(1)229
if atk is not None and not atk.is_disabled():230
atk.click()231
page.wait_for_timeout(500)232
shot(page, 'desktop-game-after-shot')233
234
# Playback arrows: rewind and play235
if page.locator('#tl-back').count():236
# Jump to start via stepping back many times, then play237
for _ in range(8):238
page.locator('#tl-back').click()239
page.wait_for_timeout(80)240
shot(page, 'desktop-timeline-start')241
page.locator('#tl-play').click()242
# Mid-playback: wait enough for a give/shoot/move arrow to show243
page.wait_for_timeout(700)244
shot(page, 'desktop-playback-arrows')245
page.wait_for_timeout(900)246
shot(page, 'desktop-playback-arrows-2')247
# Pause, step forward, jump to present248
if page.locator('#tl-play').get_attribute('title') and 'Pause' in (page.locator('#tl-play').get_attribute('title') or ''):249
page.locator('#tl-play').click()250
page.locator('#tl-fwd').click()251
page.wait_for_timeout(200)252
shot(page, 'desktop-timeline-step')253
page.locator('#tl-live').click()254
page.wait_for_timeout(200)255
shot(page, 'desktop-timeline-live')256
257
# Settings / surrender (don't confirm)258
page.locator('#btn-settings').click()259
page.wait_for_selector('#settings-panel:not([hidden])')260
shot(page, 'desktop-settings')261
page.locator('#btn-surrender').click()262
page.wait_for_selector('#modal:not([hidden])')263
shot(page, 'desktop-surrender-confirm')264
page.locator('#modal-close').click()265
266
# --- Mobile ---267
mobile = browser.new_context(268
viewport={'width': 390, 'height': 844},269
is_mobile=True,270
has_touch=True,271
user_agent='Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',272
locale='en-GB',273
)274
mp = mobile.new_page()275
mp.goto(BASE + '/', wait_until='networkidle')276
shot(mp, 'mobile-menu-guest')277
mp.locator('#lang-current').click()278
mp.wait_for_selector('#lang-list:not([hidden])')279
shot(mp, 'mobile-lang-picker')280
281
mp.goto(BASE + '/auth.php?test=3', wait_until='networkidle')282
mp.wait_for_selector('#btn-create, #menu-user')283
shot(mp, 'mobile-menu')284
mp.locator('#btn-create').click()285
mp.wait_for_selector('#lobby:not([hidden])')286
mp.locator('#rule-ceasefire').check()287
mp.locator('#rule-ap-loot').wait_for()288
mp.wait_for_timeout(300)289
shot_full(mp, 'mobile-lobby-clock')290
mp.locator('#rule-ap-time').scroll_into_view_if_needed()291
shot(mp, 'mobile-lobby-ap-time')292
vis = mp.locator('#lobby-visibility')293
if vis.count():294
vis.scroll_into_view_if_needed()295
shot(mp, 'mobile-lobby-visibility')296
297
# Player 2's running game on mobile298
mobile2 = browser.new_context(299
viewport={'width': 390, 'height': 844},300
is_mobile=True,301
has_touch=True,302
locale='en-GB',303
)304
m2 = mobile2.new_page()305
m2.goto(BASE + '/auth.php?test=2', wait_until='networkidle')306
m2.wait_for_selector('#menu, #game, #lobby')307
if m2.locator('#games-list button').count() > 0:308
m2.locator('#games-list button').first.click()309
m2.wait_for_selector('#game:not([hidden]), #lobby:not([hidden])')310
m2.wait_for_timeout(400)311
shot(m2, 'mobile-game')312
if m2.locator('#ap-hms').count():313
shot(m2, 'mobile-game-countdown')314
# playback on mobile315
if m2.locator('#tl-play').count() and m2.locator('#game:not([hidden])').count():316
m2.locator('#tl-back').click()317
m2.locator('#tl-back').click()318
m2.locator('#tl-play').click()319
m2.wait_for_timeout(700)320
shot(m2, 'mobile-playback-arrows')321
322
desk.close()323
desk2.close()324
mobile.close()325
mobile2.close()326
browser.close()327
print('playwright done')328
329
330
if __name__ == '__main__':331
main()