Reinforcement Learning
stable-baselines3
English
Portuguese
board-game
self-play
maskable-ppo
sb3-contrib
ankh
Instructions to use heitorvcm/ankh-ppo with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- stable-baselines3
How to use heitorvcm/ankh-ppo with stable-baselines3:
from huggingface_sb3 import load_from_hub checkpoint = load_from_hub( repo_id="heitorvcm/ankh-ppo", filename="{MODEL FILENAME}.zip", ) - Notebooks
- Google Colab
- Kaggle
Ankh PPO agent (round 40) + rules, encoder and local game
Browse files- LICENSE +21 -0
- README.md +146 -0
- README_projeto_pt.md +91 -0
- ankh_env.py +117 -0
- ankh_eval.py +60 -0
- ankh_game.py +1199 -0
- ankh_map.py +570 -0
- ankh_obs.py +179 -0
- ankh_report.py +338 -0
- ankh_vec.py +199 -0
- ankh_worker.py +149 -0
- jogar.html +699 -0
- jogar.py +435 -0
- replay.py +181 -0
- report.py +14 -0
- requirements.txt +6 -0
- round_0040.zip +3 -0
- train_local.py +247 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 heitorvcm
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
library_name: stable-baselines3
|
| 4 |
+
tags:
|
| 5 |
+
- reinforcement-learning
|
| 6 |
+
- board-game
|
| 7 |
+
- self-play
|
| 8 |
+
- maskable-ppo
|
| 9 |
+
- sb3-contrib
|
| 10 |
+
- ankh
|
| 11 |
+
language:
|
| 12 |
+
- en
|
| 13 |
+
- pt
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# Ankh: Gods of Egypt — MaskablePPO agent (2–5 players)
|
| 17 |
+
|
| 18 |
+
A single neural network that plays the board game **Ankh: Gods of Egypt** with 2 to 5 players, trained with
|
| 19 |
+
`MaskablePPO` (sb3-contrib) through self-play against earlier snapshots of itself.
|
| 20 |
+
|
| 21 |
+
> **Fan project.** Not affiliated with, endorsed by, or connected to CMON, the game's designers or publishers.
|
| 22 |
+
> The game rules were re-implemented in Python from the public rulebook for research and learning. This repository
|
| 23 |
+
> contains **no** rulebook, artwork or other game assets.
|
| 24 |
+
|
| 25 |
+
**Resumo em português:** agente de PPO com máscara de ações que joga Ankh de 2 a 5 jogadores, treinado em self-play
|
| 26 |
+
(16 milhões de passos, 40 rounds). O repositório inclui o modelo, o ambiente de regras e um servidor local
|
| 27 |
+
(`jogar.py`) para jogar contra a IA no navegador. Os resultados abaixo são fracos como medida de força absoluta: veja
|
| 28 |
+
"Limitações".
|
| 29 |
+
|
| 30 |
+
## Model
|
| 31 |
+
|
| 32 |
+
| | |
|
| 33 |
+
|---|---|
|
| 34 |
+
| Algorithm | `MaskablePPO` (sb3-contrib), `MlpPolicy`, net_arch `[512, 512]` |
|
| 35 |
+
| Checkpoint | `round_0040.zip` (round 40, ≈16.0M timesteps) |
|
| 36 |
+
| Observation | 6786 floats in [0, 1], always from the point of view of the deciding seat (me + up to 4 opponents, zero-padded) |
|
| 37 |
+
| Actions | 332 discrete actions, with an action mask for every decision |
|
| 38 |
+
| Players | one network for 2, 3, 4 and 5 players |
|
| 39 |
+
| Hidden information | the encoder never reads other players' pending battle cards or Plague bids |
|
| 40 |
+
| Versions used | stable-baselines3 2.9.2, PyTorch 2.15, Gymnasium 1.4.0 |
|
| 41 |
+
|
| 42 |
+
Hyperparameters: `n_steps=128`, `n_epochs=4`, `gamma=0.995`, `gae_lambda=0.95`, `ent_coef=0.01`,
|
| 43 |
+
`learning_rate=3e-4`, batch size = `n_steps * n_envs / 4`.
|
| 44 |
+
|
| 45 |
+
## How to use
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
pip install -r requirements.txt # plus PyTorch
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Load the model (the action mask is required):
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
from huggingface_hub import hf_hub_download
|
| 55 |
+
from sb3_contrib import MaskablePPO
|
| 56 |
+
|
| 57 |
+
path = hf_hub_download("heitorvcm/ankh-ppo", "round_0040.zip")
|
| 58 |
+
model = MaskablePPO.load(path, device="cpu")
|
| 59 |
+
# obs: np.ndarray (6786,) from ankh_obs.Encoder(game).encode(decision)
|
| 60 |
+
# mask: np.ndarray (332,) from decision.mask
|
| 61 |
+
action, _ = model.predict(obs, action_masks=mask, deterministic=False)
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
The observation encoder and the rules live in this repository (`ankh_obs.py`, `ankh_game.py`); **the checkpoint is
|
| 65 |
+
useless without them**, and checkpoints from other versions of the encoder will not load.
|
| 66 |
+
|
| 67 |
+
Play against it in your browser (local server, no data leaves your machine):
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
python jogar.py --models round_0040.zip
|
| 71 |
+
# open http://127.0.0.1:8765
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Print a full text replay of a game between copies of the model (shows hidden information; debugging tool):
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
python replay.py --scenario basic_4p --seed 7 --models round_0040.zip,round_0040.zip,round_0040.zip,round_0040.zip
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
## Training setup
|
| 81 |
+
|
| 82 |
+
- **Game:** 4 scenarios (`basic_2p` … `basic_5p`), all 5 gods (Amun, Anubis, Isis, Osiris, Ra), random seat and gods
|
| 83 |
+
every game, god merging with 3+ players. Scenario data was typed by hand and is not verified against the official
|
| 84 |
+
scenario book.
|
| 85 |
+
- **Opponents:** random at the start, then snapshots of the model itself (about 50% the latest snapshot, the rest
|
| 86 |
+
mostly recent ones with some older ones).
|
| 87 |
+
- **Reward:** +1 win, −1/(P−1) loss, −1 if every god is forgotten; small dense terms: +0.02 per Devotion step gained,
|
| 88 |
+
−0.01 × mean opponent steps, +0.005 per warrior added on the board, −0.0025 × mean opponent change. The god merge
|
| 89 |
+
itself gives and takes no reward (accumulated Devotion is used).
|
| 90 |
+
- **Compute:** CPU workers for the rules, GPU for inference and updates; 40 rounds × 400k steps, ≈445 minutes.
|
| 91 |
+
|
| 92 |
+
## Results (read the caveats)
|
| 93 |
+
|
| 94 |
+
All numbers come from the training log of the last round (4,348 games against the round's snapshot opponent; ties to
|
| 95 |
+
chance are computed against `1/players`).
|
| 96 |
+
|
| 97 |
+
| Players | Games | Agent win rate | Chance (1/P) |
|
| 98 |
+
|---|---|---|---|
|
| 99 |
+
| 2 | 1052 | 57% | 50% |
|
| 100 |
+
| 3 | 1081 | 48% | 33% |
|
| 101 |
+
| 4 | 1123 | 30% | 25% |
|
| 102 |
+
| 5 | 1092 | 24% | 20% |
|
| 103 |
+
|
| 104 |
+
Overall 39% vs. roughly 32% expected by chance with this mix of player counts. Against its previous snapshot in the
|
| 105 |
+
evaluation step (160 games, deterministic agent vs. sampling opponent) it won 54%.
|
| 106 |
+
|
| 107 |
+
**Caveats**
|
| 108 |
+
|
| 109 |
+
- The only opponents were earlier copies of the same model. There is **no** evaluation against human players or
|
| 110 |
+
an independent baseline, and the evaluation against random opponents was not recorded for this run.
|
| 111 |
+
- The training win rate has been flat at ≈39–46% since round 29: no clear sign of continued improvement.
|
| 112 |
+
- Strong **seat effects**: in 2-player games the agent wins 85% as seat 0 and 27% as seat 1; with 4 players seat 0 wins
|
| 113 |
+
60% and the others 17–22%; with 5 players seat 0 is the *worst* (12%). The cause is unknown (turn order, event timing or
|
| 114 |
+
scenario setup).
|
| 115 |
+
- In two inspected replays the agent rarely used the *Move Figures* action (≈8–12% of actions) and chose the
|
| 116 |
+
*Unlock Ankh Power* action as a "pass" once all powers were unlocked (allowed by the rules). Level-3/2 powers
|
| 117 |
+
Glorious, Magnanimous and Obelisk Attuned were never unlocked by the agent or its opponents.
|
| 118 |
+
- Being in a god merge happened in 40% of 3+ player games (about 52% expected for a random seat), so there is no sign
|
| 119 |
+
that the agent seeks the merge. This is a statistic over one run, not a guarantee.
|
| 120 |
+
- Several rules interpretations are assumptions (see `README_projeto_pt.md`); the model is only as faithful as that
|
| 121 |
+
implementation.
|
| 122 |
+
|
| 123 |
+
## Intended use
|
| 124 |
+
|
| 125 |
+
Research, education and casual play against a bot. Not a strength benchmark for the real board game.
|
| 126 |
+
|
| 127 |
+
## Security note
|
| 128 |
+
|
| 129 |
+
Stable-Baselines3 checkpoints are zip files that use Python pickle. Only load checkpoints from sources you trust.
|
| 130 |
+
|
| 131 |
+
## Files
|
| 132 |
+
|
| 133 |
+
| File | What it is |
|
| 134 |
+
|---|---|
|
| 135 |
+
| `round_0040.zip` | the trained model |
|
| 136 |
+
| `ankh_game.py`, `ankh_map.py` | rules and board/scenario data |
|
| 137 |
+
| `ankh_obs.py` | observation encoder |
|
| 138 |
+
| `ankh_env.py`, `ankh_worker.py`, `ankh_vec.py`, `ankh_eval.py`, `ankh_report.py`, `train_local.py`, `report.py` | training and evaluation code |
|
| 139 |
+
| `replay.py` | text replay of games |
|
| 140 |
+
| `jogar.py`, `jogar.html` | local web game against the AI |
|
| 141 |
+
| `README_projeto_pt.md` | original project notes (Portuguese) |
|
| 142 |
+
| `LICENSE` | license of the code |
|
| 143 |
+
|
| 144 |
+
## Licence
|
| 145 |
+
|
| 146 |
+
Code and model: mit. The game itself, its name and artwork belong to their respective owners.
|
README_projeto_pt.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ankh: Gods of Egypt - IA com PPO (2 a 5 jogadores)
|
| 2 |
+
|
| 3 |
+
Ambiente de regras do Ankh para **2 a 5 jogadores**, com os 5 deuses, os 12 Poderes Ankh, os 6 Guardioes, as 7 cartas de batalha e a **fusao de deuses** (3+ jogadores). Treino com `MaskablePPO` (sb3-contrib), self-play por snapshots, CPU em varios processos + GPU em lote. Uma unica rede joga qualquer numero de jogadores.
|
| 4 |
+
|
| 5 |
+
## Estrutura
|
| 6 |
+
```
|
| 7 |
+
ankh_map.py mapa (GRID_COLUMNS), rios (RIVER) e cenarios (SCENARIOS) - editar a mao
|
| 8 |
+
ankh_game.py regras: acoes, eventos, camelos, conflito, batalha, deuses, poderes, guardioes, fusao
|
| 9 |
+
ankh_obs.py codificacao da observacao (eu + ate 4 oponentes; esconde escolhas secretas)
|
| 10 |
+
ankh_env.py env Gymnasium de um assento + recompensas
|
| 11 |
+
ankh_worker.py processo de CPU que roda varias partidas
|
| 12 |
+
ankh_vec.py VecEnv em lote (SB3) + TorchOpponent (snapshot na GPU)
|
| 13 |
+
ankh_eval.py avaliacao por deus, cenario e assento; matriz de confrontos (2 jogadores)
|
| 14 |
+
ankh_report.py estatisticas por partida, report.jsonl e relatorio.md
|
| 15 |
+
report.py regenera o relatorio de uma run
|
| 16 |
+
train_local.py treino no PC
|
| 17 |
+
replay.py imprime partidas em texto (depurar regras)
|
| 18 |
+
tests/ testes de jogo, regras, env, VecEnv, soma zero e relatorio
|
| 19 |
+
```
|
| 20 |
+
O codigo fica todo na raiz de proposito: os processos de CPU importam esses modulos.
|
| 21 |
+
|
| 22 |
+
## Treinar no PC
|
| 23 |
+
```
|
| 24 |
+
pip install -r requirements.txt # + PyTorch com CUDA
|
| 25 |
+
python train_local.py --dir ~/ankh_runs/run1
|
| 26 |
+
```
|
| 27 |
+
Rode o mesmo comando para retomar; Ctrl+C salva um checkpoint.
|
| 28 |
+
- `--players 2` (ou `2,3`) restringe os numeros de jogadores; `--scenarios basic_2p,basic_4p` escolhe cenarios. Por padrao sorteia, a cada partida, um cenario valido (2 a 5 jogadores), o assento do agente e os deuses.
|
| 29 |
+
- `--god-pool 4` treina so com o Ra (0 Amun, 1 Anubis, 2 Isis, 3 Osiris, 4 Ra). Os deuses sao sempre diferentes entre si.
|
| 30 |
+
- Cenarios com erro de dados sao ignorados com um aviso. **Hoje o `basic_5p` e ignorado**: o obelisco em `(9, 3)` cai numa casa de agua e o templo em `(9, 9)` fica fora do mapa (a coluna 9 so tem indices 0 a 8). Corrija no `SCENARIOS` e ele entra sozinho. O validador mostra os erros: `python ankh_map.py`.
|
| 31 |
+
- `python train_local.py --help` lista as demais opcoes.
|
| 32 |
+
|
| 33 |
+
## Como funciona com 3 a 5 jogadores
|
| 34 |
+
- **Assentos e entidades:** cada partida tem P assentos. O agente ocupa um assento sorteado; os outros sao jogados pelo oponente (aleatorio ou snapshot da rede), inclusive o parceiro depois de uma fusao.
|
| 35 |
+
- **Observacao:** sempre do ponto de vista de quem decide, com 4 espacos para oponentes ordenados pela ordem de turno (zeros se houver menos). O formato nao muda com o numero de jogadores.
|
| 36 |
+
- **Fusao de deuses** (fim do 3o Conflito, 3+ jogadores): o de menor Devocao e absorvido pelo 2o menor. O absorvido perde monumentos, figuras e cartas, e passa Seguidores e Guardioes ao outro; os dois tokens andam juntos; o deus fundido tem as habilidades dos dois e cada um dos dois jogadores faz **1 acao** por turno. Nas batalhas decide o jogador do deus "superior". Vencem ou perdem juntos.
|
| 37 |
+
- **Recompensa:** vitoria +1, derrota -1/(P-1) (com 2 jogadores, -1), Egito ateu `draw`; mais os termos densos de Devocao e guerreiros (media dos oponentes). Com `--zero-sum` os pesos ficam simetricos e o Egito ateu vale 0.
|
| 38 |
+
- **A fusao nao gera recompensa:** a recompensa densa usa a Devocao *acumulada* (`rdev`), que a fusao nao altera, e os guerreiros no tabuleiro. Assim a queda de Devocao do deus "superior" (que passa a ter a posicao do absorvido) e a saida do absorvido nao pagam nem cobram nada de ninguem, nem do proprio agente nem dos oponentes. Ganhos reais de Devocao depois da fusao continuam premiados. O relatorio traz uma tabela "Fusao de deuses" com a frequencia com que o agente e absorvido/superior e a taxa de vitoria em cada papel, para voce conferir que ele nao esta buscando a fusao.
|
| 39 |
+
- **Modo estrito `--merged-reward zero`:** os dois assentos de um deus fundido recebem recompensa **0** (densa e final) depois da fusao. Cuidado: sem sinal de recompensa, o agente nao aprende a jogar bem como deus fundido (que e uma parte grande das partidas com 3+ jogadores), e jogadores fracos passam a preferir a fusao a arriscar uma derrota. Por isso o padrao e `normal`.
|
| 40 |
+
- **Self-play:** um assento aprende e os demais jogam com um snapshot congelado (ou aleatorio). Com mais de 2 jogadores nao existe "soma zero" estrita entre dois lados; a recompensa acima e a aproximacao usada.
|
| 41 |
+
|
| 42 |
+
## Relatorio detalhado de cada run
|
| 43 |
+
A cada round, `--dir` recebe `report.jsonl` e o **`relatorio.md`** (mais `curvas.png` se houver matplotlib). Para regenerar: `python report.py --dir ~/ankh_runs/run1`. Traz: evolucao dos ultimos rounds; como as partidas terminam; Devocao final; batalhas e dominios; **origem da Devocao**; acoes, cartas, poderes e Guardioes; eventos raros; vantagem de posicao; vitorias **por deus**; vitorias **por numero de jogadores e por assento** (comparadas com o acaso, 1/P); matriz de confrontos entre deuses (cenarios de 2 jogadores); alertas automaticos. Os mesmos numeros vao para o TensorBoard em `ankh/...`.
|
| 44 |
+
|
| 45 |
+
## Como ler o metrics.csv
|
| 46 |
+
- `win_vs_random` / `atheist_vs_random`: o modelo contra oponentes ALEATORIOS (media de todos os deuses, cenarios e assentos). Com P jogadores o acaso e 1/P; compare com a tabela por numero de jogadores do relatorio. `w_amun ... w_ra`: a mesma taxa por deus.
|
| 47 |
+
- `win_vs_prev` / `atheist_vs_prev`: o modelo contra o ULTIMO snapshot salvo (`prev_snapshot`).
|
| 48 |
+
- `train_opponent`: contra quem o round foi TREINADO.
|
| 49 |
+
|
| 50 |
+
## Conferir as regras em texto
|
| 51 |
+
```
|
| 52 |
+
python replay.py --scenario basic_4p --seed 7 --maps
|
| 53 |
+
python replay.py --models run1/checkpoints/round_0003.zip,run1/snapshots/snap_0002.zip
|
| 54 |
+
```
|
| 55 |
+
Mostra tudo (inclusive cartas e lances secretos): cada decisao, os eventos e o que mudou. Assentos sem modelo jogam aleatoriamente.
|
| 56 |
+
|
| 57 |
+
## Fases: aleatorio -> soma zero
|
| 58 |
+
1. **Fase 1** (padrao): aprende contra oponentes aleatorios e, a partir do 1o snapshot, contra versoes antigas de si mesmo.
|
| 59 |
+
2. **Fase 2** (soma zero), partindo dos pesos da fase 1:
|
| 60 |
+
```
|
| 61 |
+
python train_local.py --dir ~/ankh_runs/fase2 --zero-sum \
|
| 62 |
+
--init-from ~/ankh_runs/run1/checkpoints/round_0010.zip --opp-random-prob 0.1
|
| 63 |
+
```
|
| 64 |
+
`--init-from` carrega os pesos e copia o checkpoint como primeiro oponente.
|
| 65 |
+
|
| 66 |
+
## Formato da rede
|
| 67 |
+
Observacao de 6786 numeros e 332 acoes, com espacos reservados. **Checkpoints de versoes anteriores nao carregam** (a observacao mudou para suportar varios oponentes): comece uma `--dir` nova.
|
| 68 |
+
|
| 69 |
+
## Dados e interpretacoes a CONFIRMAR (em ankh_game.py)
|
| 70 |
+
- `GUARDIAN_CARDS`: quais Guardioes formam as cartas de cada nivel. Assumido: nivel 1 = Satet/Mummy, nivel 2 = Apep/Giant Scorpion, nivel 3 = Androsphinx/Cat-Mummy.
|
| 71 |
+
- `GUARDIAN_SLOT`: casa (1a ou 2a) que revela o simbolo de Guardiao por nivel. Assumido: a 2a em todos os niveis e deuses.
|
| 72 |
+
- `ANUBIS_SLOTS = 3` casas para guerreiros presos.
|
| 73 |
+
- Figuras de Guardiao por numero de jogadores: 2 -> 1 de cada tipo; 3 -> 2; 4 ou 5 -> 3 (pequenos) e 2 (grandes).
|
| 74 |
+
- Escolhas automaticas: Anubis sempre prende; Isis sempre salva; Ra coloca o Sol ao invocar se houver token; Mummy volta na menor casa livre ao lado do deus; Satet empurrando um Giant Scorpion aponta as garras para o melhor alvo; na fusao, os Guardioes do absorvido passam ao outro ate o limite de 2 bases por tamanho e os tokens de Sol/Underworld do absorvido vao para o deus fundido.
|
| 75 |
+
- Obelisk Attuned: cada jogador faz todos os seus movimentos de uma vez.
|
| 76 |
+
- Underworld: so o MOVIMENTO de figuras de outros deuses e bloqueado; invocar la e permitido.
|
| 77 |
+
- Sem cartas na mao, o jogador nao joga carta; lance do Plague ate 15 Seguidores; o evento de Camelo pode ser recusado; uma rodada de lances por carta Plague.
|
| 78 |
+
- Deserto = toda celula que nao e agua nem fertil; rio `(0, 0, 'E')` da lista original lido como `'SE'`; 31 casas de Devocao, 19 vermelhas.
|
| 79 |
+
- Recompensa densa: 0.02 / 0.01 por casa de Devocao (sua / media dos oponentes) e 0.005 / 0.0025 por guerreiro no tabuleiro.
|
| 80 |
+
|
| 81 |
+
## Testes
|
| 82 |
+
```
|
| 83 |
+
python tests/test_ankh_game.py # partidas aleatorias de 2 a 5 jogadores + invariantes
|
| 84 |
+
python tests/test_rules.py # deuses, poderes, guardioes, fusao e batalhas com 3 jogadores
|
| 85 |
+
python tests/test_ankh_env.py
|
| 86 |
+
python tests/test_ankh_vec.py
|
| 87 |
+
python tests/test_zero_sum.py
|
| 88 |
+
python tests/test_merge_reward.py # a fusao nao gera recompensa; modo estrito
|
| 89 |
+
python tests/test_report.py
|
| 90 |
+
```
|
| 91 |
+
Os testes de 5 jogadores usam um `test_5p` (o `basic_5p` com as 2 coordenadas invalidas movidas), registrado so nos testes: o seu `ankh_map.py` nao e alterado.
|
ankh_env.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_env.py - Wrapper Gymnasium de um jogador contra oponentes embutidos (2 a 5 jogadores).
|
| 3 |
+
|
| 4 |
+
O agente controla um ASSENTO (`me`, sorteado a cada episodio); os demais assentos jogam
|
| 5 |
+
dentro do proprio env, com `opponent(obs, mask) -> acao` (None = aleatorio legal). O cenario
|
| 6 |
+
(e com ele o numero de jogadores) e os deuses tambem sao sorteados a cada episodio.
|
| 7 |
+
Com merged_reward="zero", os assentos de um deus fundido recebem recompensa 0 (densa e final)
|
| 8 |
+
Depois da fusao. Para self-play, troque o oponente por um snapshot do modelo com env.set_opponent(...).
|
| 9 |
+
|
| 10 |
+
Recompensa (do ponto de vista de `me`), somada a cada passo do agente:
|
| 11 |
+
|
| 12 |
+
fim de jogo : +1 vitoria, -1/(P-1) derrota (P=2: -1), draw_reward no Egito ateu
|
| 13 |
+
(padrao -1; com zero_sum=True vale 0 e os pesos dos oponentes = os do agente)
|
| 14 |
+
Devocao : + dev_gain * (casas de Devocao que EU subi)
|
| 15 |
+
- dev_opp * (media das casas que os OPONENTES subiram)
|
| 16 |
+
Guerreiros : + war_gain * (variacao liquida dos MEUS guerreiros no tabuleiro)
|
| 17 |
+
- war_opp * (media da variacao dos guerreiros dos OPONENTES)
|
| 18 |
+
|
| 19 |
+
Os termos densos sao recompensas simples, NAO shaping potencial: somados valem aprox. a
|
| 20 |
+
Devocao final, entao o agente tambem e premiado por terminar mais alto. Mantenha o total
|
| 21 |
+
denso bem abaixo do +-1 da vitoria.
|
| 22 |
+
|
| 23 |
+
Compativel com sb3-contrib MaskablePPO: env.action_masks().
|
| 24 |
+
"""
|
| 25 |
+
import numpy as np
|
| 26 |
+
import gymnasium as gym
|
| 27 |
+
from gymnasium import spaces
|
| 28 |
+
|
| 29 |
+
from ankh_game import AnkhGame
|
| 30 |
+
from ankh_map import SCENARIOS
|
| 31 |
+
from ankh_obs import Encoder
|
| 32 |
+
from ankh_worker import end_reward, merged_seat, reward_parts, snapshot
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class AnkhEnv(gym.Env):
|
| 36 |
+
metadata = {"render_modes": []}
|
| 37 |
+
|
| 38 |
+
def __init__(self, scenario=None, opponent=None, seed=None,
|
| 39 |
+
dev_gain=0.02, dev_opp=0.01, war_gain=0.005, war_opp=0.0025,
|
| 40 |
+
draw_reward=-1.0, zero_sum=False, god_pool=None, merged_reward="normal"):
|
| 41 |
+
super().__init__()
|
| 42 |
+
if zero_sum:
|
| 43 |
+
dev_opp, war_opp, draw_reward = dev_gain, war_gain, 0.0
|
| 44 |
+
scenarios = [scenario] if isinstance(scenario, str) else (list(scenario) if scenario else list(SCENARIOS))
|
| 45 |
+
self.g = AnkhGame(scenarios, seed=seed, god_pool=god_pool)
|
| 46 |
+
self.enc = Encoder(self.g)
|
| 47 |
+
self.opponent = opponent
|
| 48 |
+
self.cfg = dict(dev_gain=dev_gain, dev_opp=dev_opp, war_gain=war_gain, war_opp=war_opp, draw=draw_reward,
|
| 49 |
+
merged_reward=merged_reward)
|
| 50 |
+
self.rng = np.random.default_rng(seed)
|
| 51 |
+
self.me = 0
|
| 52 |
+
dec = self.g.reset()
|
| 53 |
+
self.obs_dim = len(self.enc.encode(dec))
|
| 54 |
+
self.observation_space = spaces.Box(0.0, 1.0, (self.obs_dim,), np.float32)
|
| 55 |
+
self.action_space = spaces.Discrete(self.g.A_SIZE)
|
| 56 |
+
|
| 57 |
+
def set_opponent(self, opponent):
|
| 58 |
+
self.opponent = opponent
|
| 59 |
+
|
| 60 |
+
def action_masks(self):
|
| 61 |
+
return self.g.decision.mask
|
| 62 |
+
|
| 63 |
+
def _opponent_moves(self):
|
| 64 |
+
g = self.g
|
| 65 |
+
while not g.done and g.decision.player != self.me:
|
| 66 |
+
dec = g.decision
|
| 67 |
+
if self.opponent is None:
|
| 68 |
+
a = self.rng.choice(np.flatnonzero(dec.mask))
|
| 69 |
+
else:
|
| 70 |
+
a = int(self.opponent(self.enc.encode(dec), dec.mask))
|
| 71 |
+
g.step(a)
|
| 72 |
+
|
| 73 |
+
def reset(self, seed=None, options=None):
|
| 74 |
+
"""options: scenario (nome), me (assento), god_me, god_opp (so com 2 jogadores)."""
|
| 75 |
+
super().reset(seed=seed)
|
| 76 |
+
if seed is not None:
|
| 77 |
+
self.rng = np.random.default_rng(seed)
|
| 78 |
+
opts = options or {}
|
| 79 |
+
scen = opts.get("scenario") or self.g.scenarios[int(self.rng.integers(len(self.g.scenarios)))]
|
| 80 |
+
P = SCENARIOS[scen]["n_players"]
|
| 81 |
+
self.me = int(opts.get("me", self.rng.integers(P))) % P
|
| 82 |
+
gods = None
|
| 83 |
+
if "god_me" in opts or "god_opp" in opts:
|
| 84 |
+
pool = list(self.g.god_pool)
|
| 85 |
+
gods = [None] * P
|
| 86 |
+
if "god_me" in opts:
|
| 87 |
+
gods[self.me] = int(opts["god_me"])
|
| 88 |
+
if "god_opp" in opts and P == 2:
|
| 89 |
+
gods[1 - self.me] = int(opts["god_opp"])
|
| 90 |
+
for s in range(P):
|
| 91 |
+
if gods[s] is None:
|
| 92 |
+
free = [x for x in pool if x not in gods] or pool
|
| 93 |
+
gods[s] = int(self.rng.choice(free))
|
| 94 |
+
self.g.reset(seed=int(self.rng.integers(2**31)), gods=gods, scenario=scen)
|
| 95 |
+
self._opponent_moves()
|
| 96 |
+
self._prev = snapshot(self.g, self.me)
|
| 97 |
+
return self.enc.encode(self.g.decision), {"me": self.me, "scenario": scen}
|
| 98 |
+
|
| 99 |
+
def step(self, action):
|
| 100 |
+
g = self.g
|
| 101 |
+
g.step(int(action))
|
| 102 |
+
self._opponent_moves()
|
| 103 |
+
before, now = self._prev, snapshot(g, self.me)
|
| 104 |
+
self._prev = now
|
| 105 |
+
zero = self.cfg["merged_reward"] == "zero" and merged_seat(g, self.me)
|
| 106 |
+
r_dev, r_war = (0.0, 0.0) if zero else reward_parts(self.cfg, before, now)
|
| 107 |
+
info = {"r_dev": r_dev, "r_war": r_war}
|
| 108 |
+
if g.done:
|
| 109 |
+
r = g.rep[self.me]
|
| 110 |
+
r_end = 0.0 if zero else end_reward(self.cfg, r, g.winner, g.P)
|
| 111 |
+
opp0 = next((e for e in range(g.P) if e != r and g.rep[e] == e), None)
|
| 112 |
+
info.update(r_end=r_end, winner=g.winner, me=self.me, entity=r,
|
| 113 |
+
won=(g.winner == r), god_me=g.god[r],
|
| 114 |
+
god_opp=g.god[opp0] if opp0 is not None else None, summary=g.summary(self.me))
|
| 115 |
+
obs = np.zeros(self.obs_dim, np.float32)
|
| 116 |
+
return obs, r_dev + r_war + r_end, True, False, info
|
| 117 |
+
return self.enc.encode(g.decision), r_dev + r_war, False, False, info
|
ankh_eval.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_eval.py - Avaliacao: o modelo joga cada deus, em cada cenario (2 a 5 jogadores) e em todos os
|
| 3 |
+
assentos, contra oponentes (None = aleatorios) que recebem deuses diferentes.
|
| 4 |
+
"""
|
| 5 |
+
from ankh_env import AnkhEnv
|
| 6 |
+
from ankh_map import SCENARIOS
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def evaluate(model, n_per_god=4, opponent=None, god_pool=None, seed=12345, agg=None, scenarios=None):
|
| 10 |
+
"""Devolve (vitorias, egito_ateu, vitorias_por_deus {deus: taxa}) do modelo (deterministico).
|
| 11 |
+
`n_per_god` = partidas por deus E por cenario (os assentos se alternam).
|
| 12 |
+
Se `agg` (ankh_report.Agg) for dado, acumula o resumo detalhado de cada partida."""
|
| 13 |
+
env = AnkhEnv(scenario=scenarios, seed=seed, opponent=opponent, god_pool=god_pool)
|
| 14 |
+
pool, scens = list(env.g.god_pool), list(env.g.scenarios)
|
| 15 |
+
wins = draws = total = 0
|
| 16 |
+
by_god = {}
|
| 17 |
+
for god in pool:
|
| 18 |
+
w = n = 0
|
| 19 |
+
for sc in scens:
|
| 20 |
+
P = SCENARIOS[sc]["n_players"]
|
| 21 |
+
for ep in range(n_per_god):
|
| 22 |
+
obs, _ = env.reset(options={"scenario": sc, "me": ep % P, "god_me": god})
|
| 23 |
+
done = False
|
| 24 |
+
while not done:
|
| 25 |
+
a, _ = model.predict(obs, action_masks=env.action_masks(), deterministic=True)
|
| 26 |
+
obs, r, done, _, info = env.step(int(a))
|
| 27 |
+
w += bool(info["won"])
|
| 28 |
+
n += 1
|
| 29 |
+
draws += info["winner"] is None
|
| 30 |
+
if agg is not None:
|
| 31 |
+
agg.add(info["summary"])
|
| 32 |
+
by_god[god] = w / max(n, 1)
|
| 33 |
+
wins += w
|
| 34 |
+
total += n
|
| 35 |
+
return wins / total, draws / total, by_god
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def evaluate_matrix(model, opponent=None, god_pool=None, n_per_pair=3, seed=777, scenarios=None):
|
| 39 |
+
"""Vitorias do modelo para cada par (deus do modelo, deus do oponente) em cenarios de 2 jogadores:
|
| 40 |
+
{"a-b": [partidas, vitorias]}."""
|
| 41 |
+
env = AnkhEnv(scenario=scenarios, seed=seed, opponent=opponent, god_pool=god_pool)
|
| 42 |
+
two = [s for s in env.g.scenarios if SCENARIOS[s]["n_players"] == 2]
|
| 43 |
+
if not two:
|
| 44 |
+
return {}
|
| 45 |
+
pool = list(env.g.god_pool)
|
| 46 |
+
out = {}
|
| 47 |
+
for a in pool:
|
| 48 |
+
for b in pool:
|
| 49 |
+
if a == b and len(pool) > 1:
|
| 50 |
+
continue
|
| 51 |
+
w = 0
|
| 52 |
+
for ep in range(n_per_pair):
|
| 53 |
+
obs, _ = env.reset(options={"scenario": two[0], "me": ep % 2, "god_me": a, "god_opp": b})
|
| 54 |
+
done = False
|
| 55 |
+
while not done:
|
| 56 |
+
act, _ = model.predict(obs, action_masks=env.action_masks(), deterministic=True)
|
| 57 |
+
obs, r, done, _, info = env.step(int(act))
|
| 58 |
+
w += bool(info["won"])
|
| 59 |
+
out[f"{a}-{b}"] = [n_per_pair, int(w)]
|
| 60 |
+
return out
|
ankh_game.py
ADDED
|
@@ -0,0 +1,1199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_game.py - Nucleo de regras do Ankh: Gods of Egypt (v2).
|
| 3 |
+
|
| 4 |
+
Escopo
|
| 5 |
+
------
|
| 6 |
+
* 2 jogadores (sem fusao de deuses), cenarios de ankh_map.SCENARIOS.
|
| 7 |
+
* Os 5 deuses com suas habilidades (Amun, Anubis, Isis, Osiris, Ra).
|
| 8 |
+
* Os 12 Poderes Ankh e a acao Desbloquear de verdade (custo em Seguidores).
|
| 9 |
+
* Os 6 Guardioes (Mummy, Satet, Apep, Giant Scorpion, Androsphinx, Cat-Mummy).
|
| 10 |
+
* As 7 cartas de batalha.
|
| 11 |
+
|
| 12 |
+
Interface
|
| 13 |
+
---------
|
| 14 |
+
g = AnkhGame("basic_2p", seed=0)
|
| 15 |
+
dec = g.reset() # Decision(player, phase, mask, info) ou None
|
| 16 |
+
while dec is not None:
|
| 17 |
+
a = escolha entre np.flatnonzero(dec.mask)
|
| 18 |
+
dec = g.step(a)
|
| 19 |
+
g.winner # 0, 1 ou None (empate / Egito ateu)
|
| 20 |
+
|
| 21 |
+
Cada step e UMA decisao de UM jogador. Escolhas secretas (carta, lance do Plague)
|
| 22 |
+
sao pedidas em sequencia; o observador deve esconder g.pending_card / g.pending_bid.
|
| 23 |
+
O jogo e um gerador Python: o estado NAO pode ser copiado (sem deepcopy/MCTS).
|
| 24 |
+
|
| 25 |
+
DADOS E INTERPRETACOES A CONFIRMAR (marcados com [ASSUMIDO])
|
| 26 |
+
------------------------------------------------------------
|
| 27 |
+
* GUARDIAN_CARDS: quais Guardioes formam cada carta de nivel (o manual nao diz).
|
| 28 |
+
* GUARDIAN_SLOT: em qual das 2 casas da fileira inferior do painel de cada deus
|
| 29 |
+
fica o simbolo de Guardiao de cada nivel (so o nivel 1 do Amun aparece no manual).
|
| 30 |
+
* ANUBIS_SLOTS = 3 casas para guerreiros presos.
|
| 31 |
+
* Escolhas automaticas (sem decisao do jogador): Anubis sempre prende 1 guerreiro
|
| 32 |
+
quando ha vaga; Isis sempre salva figuras protegidas; Ra coloca o Sol no figura
|
| 33 |
+
invocada quando ha token; Mummy volta na menor casa livre ao lado do deus; Satet
|
| 34 |
+
empurrando um Giant Scorpion aponta as garras para o melhor alvo.
|
| 35 |
+
* Obelisk Attuned: cada jogador faz todos os seus movimentos de uma vez (o manual
|
| 36 |
+
manda alternar 1 figura por vez).
|
| 37 |
+
* Sem cartas na mao, o jogador nao joga carta; lance do Plague ate BID_MAX; o
|
| 38 |
+
evento de Camelo pode ser recusado; uma rodada de lances por carta Plague.
|
| 39 |
+
* Underworld: so o MOVIMENTO e bloqueado para figuras de outros deuses (como no texto).
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
from dataclasses import dataclass, field
|
| 43 |
+
from enum import IntEnum
|
| 44 |
+
|
| 45 |
+
import numpy as np
|
| 46 |
+
|
| 47 |
+
from ankh_map import DIRECTIONS, SCENARIOS, build_board, components, edge, load_scenario, nbrs
|
| 48 |
+
|
| 49 |
+
# ---------------------------------------------------------------------------
|
| 50 |
+
# Constantes de regras
|
| 51 |
+
# ---------------------------------------------------------------------------
|
| 52 |
+
TRACK_LEN = 31 # casas da Devocao; a ultima (indice 30) vence o jogo
|
| 53 |
+
TOP = TRACK_LEN - 1
|
| 54 |
+
RED_SPACES = 19 # casas vermelhas (indices 0..RED_SPACES-1) - confirmado
|
| 55 |
+
ACTION_END = 6
|
| 56 |
+
ACTION_START = {2: 3, 3: 2, 4: 1, 5: 0}
|
| 57 |
+
EVENTS = (["ctrl"] * 3 + ["conf", "camel"] + ["ctrl"] * 2 + ["conf", "camel"]
|
| 58 |
+
+ ["ctrl"] * 2 + ["conf", "camel"] + ["ctrl"] * 2 + ["conf", "ctrl", "conf"])
|
| 59 |
+
assert len(EVENTS) == 18
|
| 60 |
+
N_TOKENS = 8
|
| 61 |
+
CAMELS_TOTAL = 30
|
| 62 |
+
MAX_LINE = 6
|
| 63 |
+
MIN_REGION = 6
|
| 64 |
+
BID_MAX = 15
|
| 65 |
+
K_LINES = 128
|
| 66 |
+
N_CHOICE = 16
|
| 67 |
+
|
| 68 |
+
# cartas de batalha
|
| 69 |
+
PLAGUE, BUILD, CHARIOTS, CYCLE, DROUGHT, FLOOD, MIRACLE = range(7)
|
| 70 |
+
CARD_NAMES = ["plague", "build", "chariots", "cycle", "drought", "flood", "miracle"]
|
| 71 |
+
CARD_BONUS = [1, 0, 3, 0, 1, 0, 0]
|
| 72 |
+
MON_TYPES = ["obelisk", "temple", "pyramid"]
|
| 73 |
+
|
| 74 |
+
# deuses
|
| 75 |
+
GODS = ["amun", "anubis", "isis", "osiris", "ra"]
|
| 76 |
+
AMUN, ANUBIS, ISIS, OSIRIS, RA = range(5)
|
| 77 |
+
|
| 78 |
+
# poderes Ankh (os mesmos 12 para todos os deuses)
|
| 79 |
+
(COMMANDING, INSPIRING, OMNIPRESENT, REVERED, RESPLENDENT, OBELISK_ATT, TEMPLE_ATT, PYRAMID_ATT,
|
| 80 |
+
GLORIOUS, MAGNANIMOUS, BOUNTIFUL, WORSHIPFUL) = range(12)
|
| 81 |
+
POWER_NAMES = ["commanding", "inspiring", "omnipresent", "revered", "resplendent", "obelisk_attuned",
|
| 82 |
+
"temple_attuned", "pyramid_attuned", "glorious", "magnanimous", "bountiful", "worshipful"]
|
| 83 |
+
POWERS_BY_LEVEL = {1: [0, 1, 2, 3], 2: [4, 5, 6, 7], 3: [8, 9, 10, 11]}
|
| 84 |
+
|
| 85 |
+
# tipos de figura
|
| 86 |
+
GOD_K, WARRIOR_K, MUMMY, SATET, APEP, SCORPION, ANDRO, CATMUMMY = range(1, 9)
|
| 87 |
+
KIND_NAMES = {1: "deus", 2: "guerreiro", 3: "mummy", 4: "satet", 5: "apep",
|
| 88 |
+
6: "giant_scorpion", 7: "androsphinx", 8: "cat_mummy"}
|
| 89 |
+
GUARDIAN_KINDS = (MUMMY, SATET, APEP, SCORPION, ANDRO, CATMUMMY)
|
| 90 |
+
GUARDIAN_SIZE = {MUMMY: "small", SATET: "small", CATMUMMY: "small",
|
| 91 |
+
APEP: "large", SCORPION: "large", ANDRO: "large"}
|
| 92 |
+
GUARDIAN_CARDS = {1: [SATET, MUMMY], 2: [APEP, SCORPION], 3: [ANDRO, CATMUMMY]} # [ASSUMIDO]
|
| 93 |
+
GUARDIAN_SLOT = {g: [1, 1, 1] for g in range(5)} # [ASSUMIDO] casa (0 ou 1) que revela o simbolo
|
| 94 |
+
ANUBIS_SLOTS = 3 # [ASSUMIDO]
|
| 95 |
+
CYCLIC = ["N", "NE", "SE", "S", "SW", "NW"] # ordem das 6 direcoes ao redor de um hexagono
|
| 96 |
+
|
| 97 |
+
# Espacos RESERVADOS (formato fixo para crescer sem invalidar pesos)
|
| 98 |
+
N_POWERS = 12
|
| 99 |
+
N_GODS = 5
|
| 100 |
+
N_FIG_TYPES = 8 # 0 guerreiro (reserva), 1 guerreiro preso, 2..7 guardioes (tipo - 1)
|
| 101 |
+
N_EXTRA = 32
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Phase(IntEnum):
|
| 105 |
+
CHOOSE_ACTION = 0
|
| 106 |
+
MOVE_SELECT = 1
|
| 107 |
+
MOVE_DEST = 2
|
| 108 |
+
SUMMON_DEST = 3
|
| 109 |
+
CONTROL_PICK = 4
|
| 110 |
+
CAMEL_LINE = 5
|
| 111 |
+
CAMEL_KEEP = 6
|
| 112 |
+
CAMEL_SWAP = 7
|
| 113 |
+
BATTLE_CARD = 8
|
| 114 |
+
BUILD_TYPE = 9
|
| 115 |
+
BUILD_CELL = 10
|
| 116 |
+
BID = 11
|
| 117 |
+
TIEBREAK = 12
|
| 118 |
+
UNLOCK_PICK = 13
|
| 119 |
+
SUMMON_TYPE = 14
|
| 120 |
+
AMUN_DECLARE = 15
|
| 121 |
+
CLAW_POINT = 16
|
| 122 |
+
PUSH_DEST = 17
|
| 123 |
+
UNDERWORLD_SRC = 18
|
| 124 |
+
UNDERWORLD_DEST = 19
|
| 125 |
+
ATTUNE_SRC = 20
|
| 126 |
+
ATTUNE_DEST = 21
|
| 127 |
+
WORSHIP = 22
|
| 128 |
+
RESERVED_A = 23
|
| 129 |
+
RESERVED_B = 24
|
| 130 |
+
RESERVED_C = 25
|
| 131 |
+
RESERVED_D = 26
|
| 132 |
+
RESERVED_E = 27
|
| 133 |
+
RESERVED_F = 28
|
| 134 |
+
RESERVED_G = 29
|
| 135 |
+
RESERVED_H = 30
|
| 136 |
+
RESERVED_I = 31
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclass
|
| 140 |
+
class Decision:
|
| 141 |
+
player: int
|
| 142 |
+
phase: Phase
|
| 143 |
+
mask: np.ndarray
|
| 144 |
+
info: dict = field(default_factory=dict)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class GameEnd(Exception):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class AnkhGame:
|
| 152 |
+
def __init__(self, scenario="basic_2p", seed=None, board=None, god_pool=None):
|
| 153 |
+
self.board = board if board is not None else build_board() # Board e somente leitura
|
| 154 |
+
names = [scenario] if isinstance(scenario, str) else list(scenario)
|
| 155 |
+
self.scenarios, self.skipped = [], {}
|
| 156 |
+
for n in names: # cenarios com erro de dados sao ignorados
|
| 157 |
+
errs = load_scenario(self.board, SCENARIOS[n]).errors
|
| 158 |
+
if errs:
|
| 159 |
+
self.skipped[n] = errs
|
| 160 |
+
else:
|
| 161 |
+
self.scenarios.append(n)
|
| 162 |
+
if not self.scenarios:
|
| 163 |
+
raise ValueError(f"nenhum cenario valido: {self.skipped}")
|
| 164 |
+
self.scenario = self.scenarios[0]
|
| 165 |
+
self.P = SCENARIOS[self.scenario]["n_players"]
|
| 166 |
+
self._scenario_override = None
|
| 167 |
+
self.god_pool = list(god_pool) if god_pool else list(range(N_GODS))
|
| 168 |
+
self.rng = np.random.default_rng(seed)
|
| 169 |
+
b = self.board
|
| 170 |
+
self.N = len(b.cells)
|
| 171 |
+
self.ax = [b.axial(rc) for rc in b.cells]
|
| 172 |
+
self.ax2i = {a: i for i, a in enumerate(self.ax)}
|
| 173 |
+
self.terrain = [b.terrain[rc] for rc in b.cells]
|
| 174 |
+
self.is_land = [t != "W" for t in self.terrain]
|
| 175 |
+
self.dist = b.move_dist
|
| 176 |
+
self.nb = [[b.idx[b.step(rc, d)] for d in DIRECTIONS if b.step(rc, d) is not None]
|
| 177 |
+
for rc in b.cells]
|
| 178 |
+
self.cyc_nb = [[(b.idx[b.step(rc, d)] if b.step(rc, d) is not None else -1) for d in CYCLIC]
|
| 179 |
+
for rc in b.cells]
|
| 180 |
+
N = self.N
|
| 181 |
+
self.A_TRACK = 0
|
| 182 |
+
self.A_CELL = 4
|
| 183 |
+
self.A_DONE = self.A_CELL + N
|
| 184 |
+
self.A_CARD = self.A_DONE + 1
|
| 185 |
+
self.A_BID = self.A_CARD + 7
|
| 186 |
+
self.A_YESNO = self.A_BID + BID_MAX + 1
|
| 187 |
+
self.A_BTYPE = self.A_YESNO + 2
|
| 188 |
+
self.A_CAMEL = self.A_BTYPE + 4
|
| 189 |
+
self.A_CHOICE = self.A_CAMEL + K_LINES + 1
|
| 190 |
+
self.A_POWER = self.A_CHOICE + N_CHOICE
|
| 191 |
+
self.A_FIG = self.A_POWER + N_POWERS
|
| 192 |
+
self.A_EXTRA = self.A_FIG + N_FIG_TYPES
|
| 193 |
+
self.A_SIZE = self.A_EXTRA + N_EXTRA
|
| 194 |
+
self.decision = None
|
| 195 |
+
self.done = True
|
| 196 |
+
self._gods_override = None
|
| 197 |
+
|
| 198 |
+
# ------------------------------------------------------------------
|
| 199 |
+
# API
|
| 200 |
+
# ------------------------------------------------------------------
|
| 201 |
+
def reset(self, seed=None, gods=None, scenario=None):
|
| 202 |
+
"""gods: um deus por jogador ou None (sorteia do god_pool); scenario: nome ou None (sorteia)."""
|
| 203 |
+
if seed is not None:
|
| 204 |
+
self.rng = np.random.default_rng(seed)
|
| 205 |
+
self._gods_override = gods
|
| 206 |
+
self._scenario_override = scenario
|
| 207 |
+
self._setup()
|
| 208 |
+
self.done = False
|
| 209 |
+
self.winner = None
|
| 210 |
+
self.steps = 0
|
| 211 |
+
self._gen = self._main()
|
| 212 |
+
self.decision = self._advance(None)
|
| 213 |
+
return self.decision
|
| 214 |
+
|
| 215 |
+
def step(self, action):
|
| 216 |
+
if self.done:
|
| 217 |
+
raise RuntimeError("jogo terminou; chame reset()")
|
| 218 |
+
d = self.decision
|
| 219 |
+
if not (0 <= action < self.A_SIZE and d.mask[action]):
|
| 220 |
+
raise ValueError(f"acao ilegal {action} na fase {d.phase.name}")
|
| 221 |
+
self.steps += 1
|
| 222 |
+
self.decision = self._advance(int(action))
|
| 223 |
+
return self.decision
|
| 224 |
+
|
| 225 |
+
def legal_actions(self):
|
| 226 |
+
return np.flatnonzero(self.decision.mask)
|
| 227 |
+
|
| 228 |
+
def _advance(self, a):
|
| 229 |
+
try:
|
| 230 |
+
return self._gen.send(a)
|
| 231 |
+
except (GameEnd, StopIteration):
|
| 232 |
+
self.done = True
|
| 233 |
+
return None
|
| 234 |
+
|
| 235 |
+
# ------------------------------------------------------------------
|
| 236 |
+
# Setup
|
| 237 |
+
# ------------------------------------------------------------------
|
| 238 |
+
def _setup(self):
|
| 239 |
+
N, b = self.N, self.board
|
| 240 |
+
name = self._scenario_override or self.scenarios[int(self.rng.integers(len(self.scenarios)))]
|
| 241 |
+
self.scenario = name
|
| 242 |
+
P = self.P = SCENARIOS[name]["n_players"]
|
| 243 |
+
setup = load_scenario(b, SCENARIOS[name])
|
| 244 |
+
assert not setup.errors, setup.errors
|
| 245 |
+
self.fig_owner = [-1] * N
|
| 246 |
+
self.fig_kind = [0] * N
|
| 247 |
+
self.fig_sun = [False] * N # Ra: figura Radiant
|
| 248 |
+
self.claw = [None] * N # Giant Scorpion: orientacao das garras (0..5)
|
| 249 |
+
self.mon_type = [None] * N
|
| 250 |
+
self.mon_owner = [-1] * N
|
| 251 |
+
self.warriors_pool = [6] * P
|
| 252 |
+
self.followers = [1] * P
|
| 253 |
+
self.ankh_pool = [9] * P
|
| 254 |
+
self.supply = {t: 10 for t in MON_TYPES}
|
| 255 |
+
for kind, rc, owner in setup.monuments:
|
| 256 |
+
i = b.idx[rc]
|
| 257 |
+
self.mon_type[i] = kind
|
| 258 |
+
self.supply[kind] -= 1
|
| 259 |
+
if owner is not None:
|
| 260 |
+
self.mon_owner[i] = owner
|
| 261 |
+
self.ankh_pool[owner] -= 1
|
| 262 |
+
for p, figs in setup.figures.items():
|
| 263 |
+
for kind, rc in figs:
|
| 264 |
+
i = b.idx[rc]
|
| 265 |
+
self.fig_owner[i] = p
|
| 266 |
+
self.fig_kind[i] = GOD_K if kind == "god" else WARRIOR_K
|
| 267 |
+
if kind == "warrior":
|
| 268 |
+
self.warriors_pool[p] -= 1
|
| 269 |
+
self.camel_edges = set(setup.camel_edges)
|
| 270 |
+
self.camel_supply = CAMELS_TOTAL - len(self.camel_edges)
|
| 271 |
+
self.tokens = {}
|
| 272 |
+
for ri, tok in setup.conflict_order.items():
|
| 273 |
+
self.tokens[frozenset(self.ax2i[a] for a in setup.regions[ri])] = tok
|
| 274 |
+
self._recompute_regions()
|
| 275 |
+
# devocao
|
| 276 |
+
self.dev_pos = [0] * P
|
| 277 |
+
self.stacks = [[] for _ in range(TRACK_LEN)]
|
| 278 |
+
for p in reversed(range(P)):
|
| 279 |
+
self.stacks[0].append(p)
|
| 280 |
+
self.rdev = [0] * P # Devocao acumulada para RECOMPENSA (a fusao nao a altera)
|
| 281 |
+
self.alive = [True] * P # por ENTIDADE (deus); a fusao junta dois assentos
|
| 282 |
+
self.rep = list(range(P)) # assento -> entidade que ele controla
|
| 283 |
+
self.god2 = [None] * P # segundo deus de uma entidade fundida
|
| 284 |
+
self.merged = None # (entidade, assento absorvido) apos a fusao
|
| 285 |
+
self.markers = [ACTION_START[P]] * 4
|
| 286 |
+
self.event_idx = 0
|
| 287 |
+
self.conflicts_done = 0
|
| 288 |
+
self.hand = [set(range(7)) for _ in range(P)]
|
| 289 |
+
self.used = [[] for _ in range(P)]
|
| 290 |
+
self.pending_card = [None] * P
|
| 291 |
+
self.pending_bid = [None] * P
|
| 292 |
+
self.tiebreak_holder = None
|
| 293 |
+
self.tiebreak_available = False
|
| 294 |
+
self.turn_first = None
|
| 295 |
+
self.cur_region = None
|
| 296 |
+
self.cur_cards = None
|
| 297 |
+
self.cur = 0
|
| 298 |
+
# deuses, poderes, guardioes
|
| 299 |
+
gods = self._gods_override
|
| 300 |
+
if gods is None:
|
| 301 |
+
gods = self.rng.choice(self.god_pool, size=P, replace=len(self.god_pool) < P)
|
| 302 |
+
assert len(gods) == P, f"{P} deuses necessarios, recebi {len(gods)}"
|
| 303 |
+
self.god = [int(x) for x in gods]
|
| 304 |
+
self.powers = [set() for _ in range(P)]
|
| 305 |
+
self.unlock_next = [0] * P
|
| 306 |
+
self.g_card = {l: GUARDIAN_CARDS[l][int(self.rng.integers(2))] for l in (1, 2, 3)}
|
| 307 |
+
small, large = {2: 1, 3: 2}.get(P, 3), {2: 1, 3: 2}.get(P, 2)
|
| 308 |
+
self.g_supply = {l: (small if GUARDIAN_SIZE[self.g_card[l]] == "small" else large) for l in (1, 2, 3)}
|
| 309 |
+
self.gpool = [[] for _ in range(P)]
|
| 310 |
+
self.bases_used = {"small": [0] * P, "large": [0] * P}
|
| 311 |
+
self.sun_left = [3 if g == RA else 0 for g in self.god]
|
| 312 |
+
self.uw_off = [3 if g == OSIRIS else 0 for g in self.god]
|
| 313 |
+
self.underworld = [False] * N
|
| 314 |
+
self.trapped = [[] for _ in range(P)] # trapped[a] = donos dos guerreiros presos por Anubis a
|
| 315 |
+
self.amun_used = False
|
| 316 |
+
self.amun_declared = {}
|
| 317 |
+
self.cat_pending = []
|
| 318 |
+
self.stats = self._new_stats()
|
| 319 |
+
|
| 320 |
+
def _new_stats(self):
|
| 321 |
+
P = self.P
|
| 322 |
+
return {"end_reason": None, "actions": [[0] * 4 for _ in range(P)],
|
| 323 |
+
"dev_src": [{} for _ in range(P)], "dev_lost": [0] * P,
|
| 324 |
+
"battles": 0, "battle_wins": [0] * P, "battle_ties": 0, "dominations": [0] * P,
|
| 325 |
+
"cards": [[0] * 7 for _ in range(P)], "kills": [0] * P,
|
| 326 |
+
"unlocks": [[] for _ in range(P)], "guardians": [[] for _ in range(P)],
|
| 327 |
+
"followers_action": [0] * P, "monuments_destroyed": 0, "tiebreak_used": 0,
|
| 328 |
+
"amun_double": 0, "pushes": 0, "underworld_moves": 0, "builds": [0] * P,
|
| 329 |
+
"plague_rounds": 0}
|
| 330 |
+
|
| 331 |
+
def summary(self, me=0):
|
| 332 |
+
"""Resumo da partida do ponto de vista do ASSENTO `me`: pares [eu, media dos oponentes]."""
|
| 333 |
+
r = self.rep[me]
|
| 334 |
+
opps = [e for e in range(self.P) if e != r and self.rep[e] == e]
|
| 335 |
+
st = self.stats
|
| 336 |
+
mean = lambda xs: (sum(xs) / len(xs)) if xs else 0.0
|
| 337 |
+
num = lambda x: [x[r], mean([x[e] for e in opps])]
|
| 338 |
+
vec = lambda x: [list(x[r]), [mean([x[e][k] for e in opps]) for k in range(len(x[r]))]]
|
| 339 |
+
|
| 340 |
+
def dsrc(x):
|
| 341 |
+
keys = set().union(*[set(x[e]) for e in opps]) if opps else set()
|
| 342 |
+
return [dict(x[r]), {k: mean([x[e].get(k, 0) for e in opps]) for k in keys}]
|
| 343 |
+
|
| 344 |
+
result = "draw" if self.winner is None else ("win" if self.winner == r else "loss")
|
| 345 |
+
return {
|
| 346 |
+
"result": result, "me_first": me == 0, "me_seat": me, "n_players": self.P,
|
| 347 |
+
"scenario": self.scenario, "merged": self.merged is not None,
|
| 348 |
+
"merge_role": None if self.merged is None else (
|
| 349 |
+
"superior" if me == self.merged[0] else "absorvido" if me == self.merged[1] else None),
|
| 350 |
+
"god": [self.god[r], self.god[opps[0]] if opps else None], "steps": self.steps,
|
| 351 |
+
"end_reason": st["end_reason"], "events": self.event_idx, "conflicts": self.conflicts_done,
|
| 352 |
+
"dev_final": num(self.dev_pos), "followers": num(self.followers),
|
| 353 |
+
"monuments": [sum(1 for m in range(self.N) if self.mon_owner[m] == e) for e in [r] + opps[:1]]
|
| 354 |
+
if len(opps) == 1 else [sum(1 for m in range(self.N) if self.mon_owner[m] == r),
|
| 355 |
+
mean([sum(1 for m in range(self.N) if self.mon_owner[m] == e) for e in opps])],
|
| 356 |
+
"powers": [sorted(self.powers[r]), sorted(set().union(*[self.powers[e] for e in opps])) if opps else []],
|
| 357 |
+
"actions": vec(st["actions"]), "dev_src": dsrc(st["dev_src"]), "dev_lost": num(st["dev_lost"]),
|
| 358 |
+
"battles": st["battles"], "battle_wins": num(st["battle_wins"]), "battle_ties": st["battle_ties"],
|
| 359 |
+
"dominations": num(st["dominations"]), "cards": vec(st["cards"]), "kills": num(st["kills"]),
|
| 360 |
+
"unlocks": [list(st["unlocks"][r]), [w for e in opps for w in st["unlocks"][e]]],
|
| 361 |
+
"guardians": [list(st["guardians"][r]), [k for e in opps for k in st["guardians"][e]]],
|
| 362 |
+
"builds": num(st["builds"]), "followers_action": num(st["followers_action"]),
|
| 363 |
+
"monuments_destroyed": st["monuments_destroyed"], "tiebreak_used": st["tiebreak_used"],
|
| 364 |
+
"amun_double": st["amun_double"], "pushes": st["pushes"], "camels": len(self.camel_edges),
|
| 365 |
+
"regions": len(self.regions),
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
def _recompute_regions(self):
|
| 369 |
+
blocked = self.board.river_edges | self.camel_edges
|
| 370 |
+
comps = components(self.board.land, blocked)
|
| 371 |
+
self.regions = [frozenset(self.ax2i[a] for a in c) for c in comps]
|
| 372 |
+
self.region_of = {i: r for r in self.regions for i in r}
|
| 373 |
+
self.adj = [[] for _ in range(self.N)] # terra-terra sem rio/camelo
|
| 374 |
+
for i in range(self.N):
|
| 375 |
+
if not self.is_land[i]:
|
| 376 |
+
continue
|
| 377 |
+
for j in self.nb[i]:
|
| 378 |
+
if self.is_land[j] and edge(self.ax[i], self.ax[j]) not in blocked:
|
| 379 |
+
self.adj[i].append(j)
|
| 380 |
+
# adjacencia completa: agua e adjacente a todas as casas ao redor
|
| 381 |
+
self.adjl = [(self.adj[i] + [j for j in self.nb[i] if not self.is_land[j]]) if self.is_land[i]
|
| 382 |
+
else list(self.nb[i]) for i in range(self.N)]
|
| 383 |
+
self.adjs = [set(x) for x in self.adjl]
|
| 384 |
+
# regiao + agua vizinha (figuras na agua participam de todas as regioes adjacentes)
|
| 385 |
+
self.region_full = {r: frozenset(set(r) | {w for i in r for w in self.nb[i] if not self.is_land[w]})
|
| 386 |
+
for r in self.regions}
|
| 387 |
+
|
| 388 |
+
# ------------------------------------------------------------------
|
| 389 |
+
# Utilidades
|
| 390 |
+
# ------------------------------------------------------------------
|
| 391 |
+
def _dec(self, player, phase, idxs, **info):
|
| 392 |
+
mask = np.zeros(self.A_SIZE, dtype=bool)
|
| 393 |
+
mask[list(idxs)] = True
|
| 394 |
+
return Decision(player, phase, mask, info)
|
| 395 |
+
|
| 396 |
+
def dev_key(self, p):
|
| 397 |
+
pos = self.dev_pos[p]
|
| 398 |
+
return (pos, self.stacks[pos].index(p))
|
| 399 |
+
|
| 400 |
+
def _asc(self, players):
|
| 401 |
+
return sorted(players, key=self.dev_key)
|
| 402 |
+
|
| 403 |
+
def gain_dev(self, p, n, bountiful=True, src="outros"):
|
| 404 |
+
"""Sobe n casas. Bountiful: +1 por 'instancia' de ganho enquanto no vermelho."""
|
| 405 |
+
if n <= 0 or not self.alive[p]:
|
| 406 |
+
return
|
| 407 |
+
ds = self.stats["dev_src"][p]
|
| 408 |
+
if bountiful and BOUNTIFUL in self.powers[p] and self.dev_pos[p] < RED_SPACES:
|
| 409 |
+
n += 1
|
| 410 |
+
ds["bountiful"] = ds.get("bountiful", 0) + 1
|
| 411 |
+
ds[src] = ds.get(src, 0) + n - 1
|
| 412 |
+
else:
|
| 413 |
+
ds[src] = ds.get(src, 0) + n
|
| 414 |
+
old = self.dev_pos[p]
|
| 415 |
+
new = min(old + n, TOP)
|
| 416 |
+
self.stacks[old].remove(p)
|
| 417 |
+
self.stacks[new].append(p)
|
| 418 |
+
self.dev_pos[p] = new
|
| 419 |
+
self.rdev[p] += new - old
|
| 420 |
+
if new == TOP:
|
| 421 |
+
self.winner = p
|
| 422 |
+
self.stats["end_reason"] = "topo"
|
| 423 |
+
raise GameEnd
|
| 424 |
+
|
| 425 |
+
def lose_dev(self, p, n):
|
| 426 |
+
if n <= 0 or not self.alive[p]:
|
| 427 |
+
return
|
| 428 |
+
self.stats["dev_lost"][p] += n
|
| 429 |
+
old = self.dev_pos[p]
|
| 430 |
+
new = max(old - n, 0)
|
| 431 |
+
self.stacks[old].remove(p)
|
| 432 |
+
self.stacks[new].append(p)
|
| 433 |
+
self.dev_pos[p] = new
|
| 434 |
+
self.rdev[p] += new - old
|
| 435 |
+
|
| 436 |
+
def board_warriors(self, e):
|
| 437 |
+
return sum(1 for i in range(self.N) if self.fig_owner[i] == e and self.fig_kind[i] == WARRIOR_K)
|
| 438 |
+
|
| 439 |
+
def _has_god(self, q, g):
|
| 440 |
+
return self.god[q] == g or self.god2[q] == g
|
| 441 |
+
|
| 442 |
+
def _empty_land(self, i):
|
| 443 |
+
return self.is_land[i] and self.fig_owner[i] == -1 and self.mon_type[i] is None
|
| 444 |
+
|
| 445 |
+
def _can_end(self, i, p):
|
| 446 |
+
"""Casa onde a figura de p pode terminar um movimento (Underworld bloqueia outros deuses)."""
|
| 447 |
+
return self._empty_land(i) and (not self.underworld[i] or self._has_god(p, OSIRIS))
|
| 448 |
+
|
| 449 |
+
def _ter(self, i):
|
| 450 |
+
return "U" if self.underworld[i] else self.terrain[i]
|
| 451 |
+
|
| 452 |
+
def _figs_in(self, region, p):
|
| 453 |
+
return [i for i in self.region_full[region] if self.fig_owner[i] == p]
|
| 454 |
+
|
| 455 |
+
def _move_fig(self, s, d):
|
| 456 |
+
self.fig_owner[d], self.fig_kind[d] = self.fig_owner[s], self.fig_kind[s]
|
| 457 |
+
self.fig_sun[d], self.claw[d] = self.fig_sun[s], self.claw[s]
|
| 458 |
+
self.fig_owner[s], self.fig_kind[s], self.fig_sun[s], self.claw[s] = -1, 0, False, None
|
| 459 |
+
|
| 460 |
+
def _place_figure(self, p, kind, i):
|
| 461 |
+
"""Coloca uma figura de p em i (invocacao): Ra atribui o Sol se houver token."""
|
| 462 |
+
self.fig_owner[i], self.fig_kind[i], self.claw[i] = p, kind, None
|
| 463 |
+
self.fig_sun[i] = False
|
| 464 |
+
if self._has_god(p, RA) and self.sun_left[p] > 0:
|
| 465 |
+
self.fig_sun[i] = True
|
| 466 |
+
self.sun_left[p] -= 1
|
| 467 |
+
|
| 468 |
+
def _neutral(self, i):
|
| 469 |
+
"""Figura cuja forca nao conta: adjacente a um Androsphinx inimigo."""
|
| 470 |
+
o = self.fig_owner[i]
|
| 471 |
+
return any(self.fig_kind[j] == ANDRO and self.fig_owner[j] not in (-1, o) for j in self.adjl[i])
|
| 472 |
+
|
| 473 |
+
def _god_strength(self, q):
|
| 474 |
+
s = 1
|
| 475 |
+
if RESPLENDENT in self.powers[q]:
|
| 476 |
+
for t in MON_TYPES:
|
| 477 |
+
if sum(1 for m in range(self.N) if self.mon_type[m] == t and self.mon_owner[m] == q) >= 3:
|
| 478 |
+
s = 3
|
| 479 |
+
if self._has_god(q, ANUBIS):
|
| 480 |
+
s += min(3, len(self.trapped[q]))
|
| 481 |
+
return s
|
| 482 |
+
|
| 483 |
+
def _strength(self, q, region, cards):
|
| 484 |
+
figs = self._figs_in(region, q)
|
| 485 |
+
if not figs:
|
| 486 |
+
return 0
|
| 487 |
+
total = 0
|
| 488 |
+
for i in figs:
|
| 489 |
+
if self._neutral(i):
|
| 490 |
+
continue
|
| 491 |
+
total += self._god_strength(q) if self.fig_kind[i] == GOD_K else 1
|
| 492 |
+
if TEMPLE_ATT in self.powers[q]:
|
| 493 |
+
for m in region:
|
| 494 |
+
if (self.mon_type[m] == "temple" and self.mon_owner[m] == q
|
| 495 |
+
and any(self.fig_owner[j] == q for j in self.adjl[m])):
|
| 496 |
+
total += 2
|
| 497 |
+
return total + sum(CARD_BONUS[c] for c in cards)
|
| 498 |
+
|
| 499 |
+
def _majorities(self, region):
|
| 500 |
+
counts = [{t: 0 for t in MON_TYPES} for _ in range(self.P)]
|
| 501 |
+
for i in region:
|
| 502 |
+
if self.mon_type[i] is not None and self.mon_owner[i] >= 0:
|
| 503 |
+
counts[self.mon_owner[i]][self.mon_type[i]] += 1
|
| 504 |
+
maj = [0] * self.P
|
| 505 |
+
for t in MON_TYPES:
|
| 506 |
+
for p in range(self.P):
|
| 507 |
+
c = counts[p][t]
|
| 508 |
+
if c > 0 and all(c > counts[q][t] for q in range(self.P) if q != p):
|
| 509 |
+
maj[p] += 1
|
| 510 |
+
return maj
|
| 511 |
+
|
| 512 |
+
def _destroy_monument(self, m):
|
| 513 |
+
if self.mon_owner[m] >= 0:
|
| 514 |
+
self.ankh_pool[self.mon_owner[m]] += 1
|
| 515 |
+
self.supply[self.mon_type[m]] += 1
|
| 516 |
+
self.mon_type[m], self.mon_owner[m] = None, -1
|
| 517 |
+
|
| 518 |
+
def _kill_pass(self, cells, killed):
|
| 519 |
+
"""Mata as figuras em `cells` (deuses nunca morrem) e aplica os efeitos de morte:
|
| 520 |
+
Anubis prende 1 guerreiro por momento, Mummy volta, Cat-Mummy agenda a penalidade,
|
| 521 |
+
o Sol de Ra volta ao painel."""
|
| 522 |
+
warriors, revive = [], []
|
| 523 |
+
for i in cells:
|
| 524 |
+
o, k = self.fig_owner[i], self.fig_kind[i]
|
| 525 |
+
if o < 0 or k == GOD_K:
|
| 526 |
+
continue
|
| 527 |
+
killed[o] += 1
|
| 528 |
+
if k == WARRIOR_K:
|
| 529 |
+
warriors.append(o)
|
| 530 |
+
else:
|
| 531 |
+
self.gpool[o].append(k)
|
| 532 |
+
if k == CATMUMMY:
|
| 533 |
+
self.cat_pending.append(o)
|
| 534 |
+
if k == MUMMY:
|
| 535 |
+
revive.append(o)
|
| 536 |
+
if self.fig_sun[i]:
|
| 537 |
+
self.sun_left[o] += 1
|
| 538 |
+
self.fig_owner[i], self.fig_kind[i], self.fig_sun[i], self.claw[i] = -1, 0, False, None
|
| 539 |
+
for a in range(self.P):
|
| 540 |
+
if self.alive[a] and self._has_god(a, ANUBIS) and len(self.trapped[a]) < ANUBIS_SLOTS:
|
| 541 |
+
for k, o in enumerate(warriors):
|
| 542 |
+
if o != a:
|
| 543 |
+
self.trapped[a].append(warriors.pop(k))
|
| 544 |
+
break
|
| 545 |
+
for o in warriors:
|
| 546 |
+
self.warriors_pool[o] += 1
|
| 547 |
+
for o in revive:
|
| 548 |
+
self._revive_mummy(o)
|
| 549 |
+
|
| 550 |
+
def _revive_mummy(self, o):
|
| 551 |
+
if MUMMY not in self.gpool[o]:
|
| 552 |
+
return
|
| 553 |
+
gc = next((i for i in range(self.N) if self.fig_owner[i] == o and self.fig_kind[i] == GOD_K), None)
|
| 554 |
+
if gc is None:
|
| 555 |
+
return
|
| 556 |
+
cand = [j for j in self.adj[gc] if self._can_end(j, o)]
|
| 557 |
+
if cand:
|
| 558 |
+
self.gpool[o].remove(MUMMY)
|
| 559 |
+
self._place_figure(o, MUMMY, min(cand))
|
| 560 |
+
|
| 561 |
+
def _flush_cat(self):
|
| 562 |
+
for o in self.cat_pending:
|
| 563 |
+
for q in range(self.P):
|
| 564 |
+
if q != o:
|
| 565 |
+
self.lose_dev(q, 1)
|
| 566 |
+
self.cat_pending = []
|
| 567 |
+
|
| 568 |
+
def _auto_claw(self, i):
|
| 569 |
+
"""Garras do Scorpion apontadas para o par de casas com mais monumentos inimigos."""
|
| 570 |
+
o, best, bk = self.fig_owner[i], -1, 0
|
| 571 |
+
for k in range(6):
|
| 572 |
+
score = 0
|
| 573 |
+
for d in (k, (k + 1) % 6):
|
| 574 |
+
j = self.cyc_nb[i][d]
|
| 575 |
+
if j >= 0 and self.mon_type[j] is not None and j in self.adjs[i]:
|
| 576 |
+
score += 2 if self.mon_owner[j] != o else -1
|
| 577 |
+
if score > best:
|
| 578 |
+
best, bk = score, k
|
| 579 |
+
self.claw[i] = bk
|
| 580 |
+
|
| 581 |
+
# ------------------------------------------------------------------
|
| 582 |
+
# Laco principal
|
| 583 |
+
# ------------------------------------------------------------------
|
| 584 |
+
def _main(self):
|
| 585 |
+
while True:
|
| 586 |
+
p = self.cur # assento da vez
|
| 587 |
+
r = self.rep[p] # entidade que ele controla
|
| 588 |
+
single = self.merged is not None and r == self.merged[0]
|
| 589 |
+
self.turn_first = None
|
| 590 |
+
first = yield self._dec(p, Phase.CHOOSE_ACTION, range(4))
|
| 591 |
+
self.turn_first = first
|
| 592 |
+
if (yield from self._perform(p, first)):
|
| 593 |
+
pass
|
| 594 |
+
elif first < 3 and not single: # deus fundido: so 1 acao por turno
|
| 595 |
+
second = yield self._dec(p, Phase.CHOOSE_ACTION, range(first + 1, 4))
|
| 596 |
+
yield from self._perform(p, second)
|
| 597 |
+
self.cur = (self.cur + 1) % self.P
|
| 598 |
+
while not self.alive[self.rep[self.cur]]:
|
| 599 |
+
self.cur = (self.cur + 1) % self.P
|
| 600 |
+
|
| 601 |
+
def _perform(self, p, line):
|
| 602 |
+
r = self.rep[p]
|
| 603 |
+
self.markers[line] += 1
|
| 604 |
+
self.stats["actions"][r][line] += 1
|
| 605 |
+
if line == 0:
|
| 606 |
+
yield from self._act_move(r)
|
| 607 |
+
elif line == 1:
|
| 608 |
+
yield from self._act_summon(r)
|
| 609 |
+
elif line == 2:
|
| 610 |
+
self._act_followers(r)
|
| 611 |
+
else:
|
| 612 |
+
yield from self._act_unlock(r)
|
| 613 |
+
if self.markers[line] < ACTION_END:
|
| 614 |
+
return False
|
| 615 |
+
kind = EVENTS[self.event_idx]
|
| 616 |
+
self.event_idx += 1
|
| 617 |
+
if kind == "ctrl":
|
| 618 |
+
yield from self._ev_control(r)
|
| 619 |
+
elif kind == "camel":
|
| 620 |
+
yield from self._ev_camel(r)
|
| 621 |
+
else:
|
| 622 |
+
yield from self._ev_conflict(r)
|
| 623 |
+
self.markers[line] = ACTION_START[self.P]
|
| 624 |
+
if self.event_idx == len(EVENTS):
|
| 625 |
+
alive = [q for q in range(self.P) if self.alive[q]]
|
| 626 |
+
self.winner = max(alive, key=self.dev_key)
|
| 627 |
+
self.stats["end_reason"] = "ultimo_evento"
|
| 628 |
+
raise GameEnd
|
| 629 |
+
return True
|
| 630 |
+
|
| 631 |
+
# ------------------------------------------------------------------
|
| 632 |
+
# Acoes
|
| 633 |
+
# ------------------------------------------------------------------
|
| 634 |
+
def _push_opts(self, j):
|
| 635 |
+
"""Casas para onde Satet pode empurrar a figura inimiga em j (1 casa)."""
|
| 636 |
+
q = self.fig_owner[j]
|
| 637 |
+
return [k for k in range(self.N) if k != j and self.dist[j, k] == 1 and self._can_end(k, q)]
|
| 638 |
+
|
| 639 |
+
def _point_claws(self, p, i, seat=None):
|
| 640 |
+
seat = self.cur if seat is None else seat
|
| 641 |
+
a = yield self._dec(seat, Phase.CLAW_POINT, [self.A_CHOICE + k for k in range(6)], src=i)
|
| 642 |
+
self.claw[i] = a - self.A_CHOICE
|
| 643 |
+
|
| 644 |
+
def _act_move(self, p):
|
| 645 |
+
moved = set()
|
| 646 |
+
while True:
|
| 647 |
+
srcs = [i for i in range(self.N) if self.fig_owner[i] == p and i not in moved]
|
| 648 |
+
if not srcs:
|
| 649 |
+
return
|
| 650 |
+
a = yield self._dec(self.cur, Phase.MOVE_SELECT, [self.A_CELL + i for i in srcs] + [self.A_DONE])
|
| 651 |
+
if a == self.A_DONE:
|
| 652 |
+
return
|
| 653 |
+
s = a - self.A_CELL
|
| 654 |
+
kind = self.fig_kind[s]
|
| 655 |
+
dests = [s] + [j for j in range(self.N) if j != s and self.dist[s, j] <= 3 and self._can_end(j, p)]
|
| 656 |
+
pushes = []
|
| 657 |
+
if kind == SATET:
|
| 658 |
+
pushes = [j for j in range(self.N) if j != s and self.dist[s, j] <= 3 and self.is_land[j]
|
| 659 |
+
and self.fig_owner[j] not in (-1, p) and self._push_opts(j)]
|
| 660 |
+
a = yield self._dec(self.cur, Phase.MOVE_DEST, [self.A_CELL + j for j in dests + pushes], src=s)
|
| 661 |
+
d = a - self.A_CELL
|
| 662 |
+
if d in pushes:
|
| 663 |
+
opts = self._push_opts(d)
|
| 664 |
+
a = yield self._dec(self.cur, Phase.PUSH_DEST, [self.A_CELL + k for k in opts], src=d)
|
| 665 |
+
k = a - self.A_CELL
|
| 666 |
+
self.stats["pushes"] += 1
|
| 667 |
+
self._move_fig(d, k)
|
| 668 |
+
if self.fig_kind[k] == SCORPION:
|
| 669 |
+
self._auto_claw(k)
|
| 670 |
+
if d != s:
|
| 671 |
+
self._move_fig(s, d)
|
| 672 |
+
if kind == SCORPION:
|
| 673 |
+
yield from self._point_claws(p, d)
|
| 674 |
+
moved.add(d)
|
| 675 |
+
|
| 676 |
+
def _summon_options(self, p, mode, pyr=None):
|
| 677 |
+
"""{tipo: [casas legais]}; tipo 0 = guerreiro do pool, 1 = guerreiro preso por Anubis, k-1 = guardiao k."""
|
| 678 |
+
N = self.N
|
| 679 |
+
if mode == "regular":
|
| 680 |
+
cells = [i for i in range(N) if self._empty_land(i) and any(
|
| 681 |
+
self.fig_owner[j] == p or (self.mon_type[j] is not None and self.mon_owner[j] == p)
|
| 682 |
+
for j in self.adjl[i])]
|
| 683 |
+
elif mode == "pyramid":
|
| 684 |
+
cells = [j for j in self.adjl[pyr] if self._empty_land(j)]
|
| 685 |
+
else: # underworld
|
| 686 |
+
cells = [i for i in range(N) if self.underworld[i] and self._empty_land(i)]
|
| 687 |
+
types = []
|
| 688 |
+
if self.warriors_pool[p] > 0:
|
| 689 |
+
types.append((0, WARRIOR_K))
|
| 690 |
+
if self.followers[p] >= 1 and any(p in tl for a, tl in enumerate(self.trapped) if a != p):
|
| 691 |
+
types.append((1, WARRIOR_K))
|
| 692 |
+
for k in sorted(set(self.gpool[p])):
|
| 693 |
+
types.append((k - 1, k))
|
| 694 |
+
out = {}
|
| 695 |
+
for t, k in types:
|
| 696 |
+
c = list(cells)
|
| 697 |
+
if k == APEP:
|
| 698 |
+
if mode == "regular":
|
| 699 |
+
c += [i for i in range(N) if not self.is_land[i] and self.fig_owner[i] == -1]
|
| 700 |
+
elif mode == "pyramid":
|
| 701 |
+
c += [j for j in self.adjl[pyr] if not self.is_land[j] and self.fig_owner[j] == -1]
|
| 702 |
+
if c:
|
| 703 |
+
out[t] = c
|
| 704 |
+
return out
|
| 705 |
+
|
| 706 |
+
def _summon_one(self, p, mode, pyr=None):
|
| 707 |
+
opts = self._summon_options(p, mode, pyr)
|
| 708 |
+
if not opts:
|
| 709 |
+
return
|
| 710 |
+
optional = mode != "regular"
|
| 711 |
+
if len(opts) == 1 and not optional:
|
| 712 |
+
t = next(iter(opts))
|
| 713 |
+
else:
|
| 714 |
+
idxs = [self.A_FIG + t for t in opts] + ([self.A_DONE] if optional else [])
|
| 715 |
+
a = yield self._dec(self.cur, Phase.SUMMON_TYPE, idxs, mode=mode)
|
| 716 |
+
if a == self.A_DONE:
|
| 717 |
+
return
|
| 718 |
+
t = a - self.A_FIG
|
| 719 |
+
a = yield self._dec(self.cur, Phase.SUMMON_DEST, [self.A_CELL + c for c in opts[t]], fig=t, mode=mode)
|
| 720 |
+
i = a - self.A_CELL
|
| 721 |
+
if t <= 1:
|
| 722 |
+
kind = WARRIOR_K
|
| 723 |
+
if t == 0:
|
| 724 |
+
self.warriors_pool[p] -= 1
|
| 725 |
+
else: # resgata guerreiro preso: paga 1 Seguidor a Anubis
|
| 726 |
+
an = next(a2 for a2, tl in enumerate(self.trapped) if a2 != p and p in tl)
|
| 727 |
+
self.trapped[an].remove(p)
|
| 728 |
+
self.followers[p] -= 1
|
| 729 |
+
self.followers[an] += 1
|
| 730 |
+
else:
|
| 731 |
+
kind = t + 1
|
| 732 |
+
self.gpool[p].remove(kind)
|
| 733 |
+
self._place_figure(p, kind, i)
|
| 734 |
+
if kind == SCORPION:
|
| 735 |
+
yield from self._point_claws(p, i)
|
| 736 |
+
|
| 737 |
+
def _act_summon(self, p):
|
| 738 |
+
if PYRAMID_ATT in self.powers[p]:
|
| 739 |
+
for pyr in [m for m in range(self.N) if self.mon_type[m] == "pyramid" and self.mon_owner[m] == p]:
|
| 740 |
+
yield from self._summon_one(p, "pyramid", pyr)
|
| 741 |
+
if self._has_god(p, OSIRIS) and any(self.underworld):
|
| 742 |
+
yield from self._summon_one(p, "underworld")
|
| 743 |
+
yield from self._summon_one(p, "regular")
|
| 744 |
+
|
| 745 |
+
def _act_followers(self, p):
|
| 746 |
+
n = sum(1 for m in range(self.N) if self.mon_type[m] is not None and self.mon_owner[m] in (-1, p)
|
| 747 |
+
and any(self.fig_owner[j] == p for j in self.adjl[m]))
|
| 748 |
+
if REVERED in self.powers[p]:
|
| 749 |
+
n += 1
|
| 750 |
+
self.followers[p] += n
|
| 751 |
+
self.stats["followers_action"][p] += n
|
| 752 |
+
|
| 753 |
+
def _gain_guardian(self, p, level):
|
| 754 |
+
k = self.g_card[level]
|
| 755 |
+
size = GUARDIAN_SIZE[k]
|
| 756 |
+
if self.g_supply[level] <= 0 or self.bases_used[size][p] >= 2:
|
| 757 |
+
return
|
| 758 |
+
self.g_supply[level] -= 1
|
| 759 |
+
self.bases_used[size][p] += 1
|
| 760 |
+
self.gpool[p].append(k)
|
| 761 |
+
self.stats["guardians"][p].append(k)
|
| 762 |
+
|
| 763 |
+
def _act_unlock(self, p):
|
| 764 |
+
n = self.unlock_next[p]
|
| 765 |
+
if n >= 6:
|
| 766 |
+
return
|
| 767 |
+
level = n // 2 + 1
|
| 768 |
+
if self.followers[p] < level:
|
| 769 |
+
return
|
| 770 |
+
avail = [w for w in POWERS_BY_LEVEL[level] if w not in self.powers[p]]
|
| 771 |
+
a = yield self._dec(self.cur, Phase.UNLOCK_PICK, [self.A_POWER + w for w in avail], level=level)
|
| 772 |
+
self.followers[p] -= level
|
| 773 |
+
self.powers[p].add(a - self.A_POWER)
|
| 774 |
+
self.stats["unlocks"][p].append(a - self.A_POWER)
|
| 775 |
+
self.unlock_next[p] += 1
|
| 776 |
+
if n % 2 == GUARDIAN_SLOT[self.god[p]][level - 1]:
|
| 777 |
+
self._gain_guardian(p, level)
|
| 778 |
+
|
| 779 |
+
# ------------------------------------------------------------------
|
| 780 |
+
# Eventos
|
| 781 |
+
# ------------------------------------------------------------------
|
| 782 |
+
def _ev_control(self, p):
|
| 783 |
+
if self.ankh_pool[p] == 0:
|
| 784 |
+
return
|
| 785 |
+
mons = [m for m in range(self.N) if self.mon_type[m] is not None]
|
| 786 |
+
neutral = any(self.mon_owner[m] == -1 for m in mons)
|
| 787 |
+
cand = []
|
| 788 |
+
for m in mons:
|
| 789 |
+
owner = self.mon_owner[m]
|
| 790 |
+
ok = owner == -1 if neutral else owner not in (-1, p)
|
| 791 |
+
if ok and any(self.fig_owner[j] == p for j in self.adjl[m]):
|
| 792 |
+
cand.append(m)
|
| 793 |
+
if not cand:
|
| 794 |
+
return
|
| 795 |
+
a = yield self._dec(self.cur, Phase.CONTROL_PICK, [self.A_CELL + m for m in cand])
|
| 796 |
+
m = a - self.A_CELL
|
| 797 |
+
if self.mon_owner[m] >= 0:
|
| 798 |
+
self.ankh_pool[self.mon_owner[m]] += 1
|
| 799 |
+
self.mon_owner[m] = p
|
| 800 |
+
self.ankh_pool[p] -= 1
|
| 801 |
+
|
| 802 |
+
# --- camelos ---
|
| 803 |
+
def legal_camel_lines(self):
|
| 804 |
+
"""Todas as linhas legais de camelos (lista de frozensets de lados)."""
|
| 805 |
+
land = self.board.land
|
| 806 |
+
blocked = self.board.river_edges | self.camel_edges
|
| 807 |
+
max_len = min(MAX_LINE, self.camel_supply)
|
| 808 |
+
|
| 809 |
+
def verts(e):
|
| 810 |
+
a, c = tuple(e)
|
| 811 |
+
return [frozenset((a, c, x)) for x in nbrs(a) & nbrs(c)]
|
| 812 |
+
|
| 813 |
+
anchors = set()
|
| 814 |
+
for e in blocked:
|
| 815 |
+
anchors.update(verts(e))
|
| 816 |
+
ev, v_edges = {}, {}
|
| 817 |
+
for a in land:
|
| 818 |
+
for c in nbrs(a) & land:
|
| 819 |
+
if a < c:
|
| 820 |
+
e = edge(a, c)
|
| 821 |
+
if e in blocked:
|
| 822 |
+
continue
|
| 823 |
+
ev[e] = verts(e)
|
| 824 |
+
for v in ev[e]:
|
| 825 |
+
v_edges.setdefault(v, []).append(e)
|
| 826 |
+
if any(x not in land for x in v): # toca agua ou borda do mapa
|
| 827 |
+
anchors.add(v)
|
| 828 |
+
|
| 829 |
+
def dfs(v, path, visited):
|
| 830 |
+
if len(path) == max_len:
|
| 831 |
+
return
|
| 832 |
+
for e in v_edges.get(v, []):
|
| 833 |
+
if e in path:
|
| 834 |
+
continue
|
| 835 |
+
u = ev[e][0] if ev[e][1] == v else ev[e][1]
|
| 836 |
+
if u in visited:
|
| 837 |
+
continue
|
| 838 |
+
new = path + [e]
|
| 839 |
+
if u in anchors:
|
| 840 |
+
yield frozenset(new)
|
| 841 |
+
else:
|
| 842 |
+
yield from dfs(u, new, visited | {u})
|
| 843 |
+
|
| 844 |
+
raw = {l for a in anchors for l in dfs(a, [], {a})}
|
| 845 |
+
reg_of = {x: r for r in components(land, blocked) for x in r}
|
| 846 |
+
legal = []
|
| 847 |
+
for line in raw:
|
| 848 |
+
e0 = next(iter(line))
|
| 849 |
+
region = reg_of[next(iter(e0))]
|
| 850 |
+
parts = components(region, blocked | line)
|
| 851 |
+
if len(parts) == 2 and all(len(c) >= MIN_REGION for c in parts):
|
| 852 |
+
legal.append(line)
|
| 853 |
+
legal.sort(key=lambda l: sorted(sorted(e) for e in l))
|
| 854 |
+
return legal
|
| 855 |
+
|
| 856 |
+
def _ev_camel(self, p):
|
| 857 |
+
lines = self.legal_camel_lines()[:K_LINES]
|
| 858 |
+
idxs = [self.A_CAMEL] + [self.A_CAMEL + 1 + k for k in range(len(lines))]
|
| 859 |
+
a = yield self._dec(self.cur, Phase.CAMEL_LINE, idxs, lines=lines)
|
| 860 |
+
k = a - self.A_CAMEL - 1
|
| 861 |
+
if k < 0:
|
| 862 |
+
return
|
| 863 |
+
line = lines[k]
|
| 864 |
+
old_regions = set(self.regions)
|
| 865 |
+
self.camel_edges |= line
|
| 866 |
+
self.camel_supply -= len(line)
|
| 867 |
+
self._recompute_regions()
|
| 868 |
+
new = sorted((r for r in self.regions if r not in old_regions), key=min)
|
| 869 |
+
old = next(r for r in old_regions if r not in set(self.regions))
|
| 870 |
+
tok = self.tokens.pop(old)
|
| 871 |
+
a = yield self._dec(self.cur, Phase.CAMEL_KEEP, [self.A_CHOICE, self.A_CHOICE + 1])
|
| 872 |
+
keep = new[a - self.A_CHOICE]
|
| 873 |
+
other = new[1 - (a - self.A_CHOICE)]
|
| 874 |
+
self.tokens[keep] = tok
|
| 875 |
+
self.tokens[other] = min(set(range(1, N_TOKENS + 1)) - set(self.tokens.values()))
|
| 876 |
+
ops = [None]
|
| 877 |
+
for x in new:
|
| 878 |
+
for y in self.regions:
|
| 879 |
+
if y != x and not (y in new and new.index(y) < new.index(x)):
|
| 880 |
+
ops.append((x, y))
|
| 881 |
+
ops = ops[:N_CHOICE]
|
| 882 |
+
a = yield self._dec(self.cur, Phase.CAMEL_SWAP, [self.A_CHOICE + k for k in range(len(ops))])
|
| 883 |
+
op = ops[a - self.A_CHOICE]
|
| 884 |
+
if op is not None:
|
| 885 |
+
x, y = op
|
| 886 |
+
self.tokens[x], self.tokens[y] = self.tokens[y], self.tokens[x]
|
| 887 |
+
|
| 888 |
+
# --- conflito ---
|
| 889 |
+
def _ev_conflict(self, trigger):
|
| 890 |
+
self.tiebreak_holder, self.tiebreak_available = trigger, True
|
| 891 |
+
self.amun_used = False
|
| 892 |
+
for q in self._asc([q for q in range(self.P) if self.alive[q]]):
|
| 893 |
+
if OMNIPRESENT in self.powers[q]:
|
| 894 |
+
self.followers[q] += sum(1 for r in self.regions if self._figs_in(r, q))
|
| 895 |
+
for i in range(self.N): # garras do Giant Scorpion
|
| 896 |
+
if self.fig_kind[i] == SCORPION and self.claw[i] is not None:
|
| 897 |
+
for d in (self.claw[i], (self.claw[i] + 1) % 6):
|
| 898 |
+
j = self.cyc_nb[i][d]
|
| 899 |
+
if j >= 0 and self.mon_type[j] is not None and j in self.adjs[i]:
|
| 900 |
+
self._destroy_monument(j)
|
| 901 |
+
self.stats["monuments_destroyed"] += 1
|
| 902 |
+
for region in sorted(self.regions, key=lambda r: self.tokens[r]):
|
| 903 |
+
players = [q for q in range(self.P) if self.alive[q] and self._figs_in(region, q)]
|
| 904 |
+
if not players:
|
| 905 |
+
continue
|
| 906 |
+
if len(players) == 1:
|
| 907 |
+
q = players[0]
|
| 908 |
+
maj = self._majorities(region)[q]
|
| 909 |
+
if maj > 0:
|
| 910 |
+
self.gain_dev(q, maj, src="maioria")
|
| 911 |
+
self.stats["dominations"][q] += 1
|
| 912 |
+
radiant = 1 if any(self.fig_sun[i] for i in self._figs_in(region, q)) else 0
|
| 913 |
+
self.gain_dev(q, 1 + radiant, src="dominio")
|
| 914 |
+
else:
|
| 915 |
+
yield from self._battle(region, players)
|
| 916 |
+
self.tiebreak_holder, self.tiebreak_available = None, False
|
| 917 |
+
self.conflicts_done += 1
|
| 918 |
+
if self.conflicts_done == 3 and self.P >= 3:
|
| 919 |
+
self._merge_gods()
|
| 920 |
+
if self.conflicts_done == 4:
|
| 921 |
+
self._forget_gods()
|
| 922 |
+
|
| 923 |
+
def _merge_gods(self):
|
| 924 |
+
"""Fim do 3o Conflito (3+ jogadores): os 2 deuses de menor Devocao se fundem.
|
| 925 |
+
Entidade resultante = deus 'superior' (2o mais baixo); o mais baixo e absorvido."""
|
| 926 |
+
alive = [q for q in range(self.P) if self.alive[q]]
|
| 927 |
+
if len(alive) < 2:
|
| 928 |
+
return
|
| 929 |
+
order = sorted(alive, key=self.dev_key)
|
| 930 |
+
L, H = order[0], order[1]
|
| 931 |
+
for m in range(self.N): # monumentos de L sao destruidos
|
| 932 |
+
if self.mon_owner[m] == L:
|
| 933 |
+
self._destroy_monument(m)
|
| 934 |
+
for i in range(self.N): # figuras: Guardioes passam para H
|
| 935 |
+
if self.fig_owner[i] == L:
|
| 936 |
+
k = self.fig_kind[i]
|
| 937 |
+
size = GUARDIAN_SIZE.get(k)
|
| 938 |
+
if size and self.bases_used[size][H] < 2:
|
| 939 |
+
self.bases_used[size][H] += 1
|
| 940 |
+
self.fig_owner[i] = H
|
| 941 |
+
if self.fig_sun[i]:
|
| 942 |
+
self.fig_sun[i] = False
|
| 943 |
+
self.sun_left[L] += 1
|
| 944 |
+
else:
|
| 945 |
+
if self.fig_sun[i]:
|
| 946 |
+
self.sun_left[L] += 1
|
| 947 |
+
self.fig_owner[i], self.fig_kind[i], self.fig_sun[i], self.claw[i] = -1, 0, False, None
|
| 948 |
+
for k in self.gpool[L]:
|
| 949 |
+
size = GUARDIAN_SIZE[k]
|
| 950 |
+
if self.bases_used[size][H] < 2:
|
| 951 |
+
self.bases_used[size][H] += 1
|
| 952 |
+
self.gpool[H].append(k)
|
| 953 |
+
self.gpool[L] = []
|
| 954 |
+
self.followers[H] += self.followers[L]
|
| 955 |
+
self.followers[L] = 0
|
| 956 |
+
self.hand[L], self.used[L] = set(), []
|
| 957 |
+
self.warriors_pool[L] = 0
|
| 958 |
+
for a in range(self.P): # guerreiros de L presos por Anubis somem
|
| 959 |
+
self.trapped[a] = [v for v in self.trapped[a] if v != L]
|
| 960 |
+
for v in self.trapped[L]: # os que L prendeu voltam aos donos
|
| 961 |
+
self.warriors_pool[v] += 1
|
| 962 |
+
self.trapped[L] = []
|
| 963 |
+
self.sun_left[H] += self.sun_left[L]
|
| 964 |
+
self.uw_off[H] += self.uw_off[L]
|
| 965 |
+
self.sun_left[L] = self.uw_off[L] = 0
|
| 966 |
+
pos = self.dev_pos[L] # os dois tokens passam a andar juntos
|
| 967 |
+
self.stacks[pos].remove(L)
|
| 968 |
+
self.stacks[self.dev_pos[H]].remove(H)
|
| 969 |
+
self.dev_pos[H] = pos
|
| 970 |
+
self.stacks[pos].insert(0, H)
|
| 971 |
+
self.alive[L] = False
|
| 972 |
+
self.rep[L] = H
|
| 973 |
+
self.god2[H] = self.god[L]
|
| 974 |
+
self.merged = (H, L)
|
| 975 |
+
self.stats["merge"] = (H, L)
|
| 976 |
+
|
| 977 |
+
def _forget_gods(self):
|
| 978 |
+
for q in range(self.P):
|
| 979 |
+
if self.alive[q] and self.dev_pos[q] < RED_SPACES:
|
| 980 |
+
self.alive[q] = False
|
| 981 |
+
self.stacks[self.dev_pos[q]].remove(q)
|
| 982 |
+
for i in range(self.N):
|
| 983 |
+
if self.fig_owner[i] == q:
|
| 984 |
+
self.fig_owner[i], self.fig_kind[i], self.fig_sun[i], self.claw[i] = -1, 0, False, None
|
| 985 |
+
if self.mon_owner[i] == q:
|
| 986 |
+
self._destroy_monument(i)
|
| 987 |
+
self.followers[q] = 0
|
| 988 |
+
if self._has_god(q, OSIRIS):
|
| 989 |
+
self.underworld = [False] * self.N
|
| 990 |
+
self.uw_off[q] = 0
|
| 991 |
+
for v in self.trapped[q]:
|
| 992 |
+
self.warriors_pool[v] += 1
|
| 993 |
+
self.trapped[q] = []
|
| 994 |
+
alive = [q for q in range(self.P) if self.alive[q]]
|
| 995 |
+
if len(alive) == 1:
|
| 996 |
+
self.winner = alive[0]
|
| 997 |
+
self.stats["end_reason"] = "ultimo_deus"
|
| 998 |
+
raise GameEnd
|
| 999 |
+
if not alive:
|
| 1000 |
+
self.winner = None
|
| 1001 |
+
self.stats["end_reason"] = "egito_ateu"
|
| 1002 |
+
raise GameEnd
|
| 1003 |
+
|
| 1004 |
+
def _attune(self, q, region):
|
| 1005 |
+
"""Obelisk Attuned: move figuras de qualquer lugar para casas vazias ao lado dos seus Obeliscos."""
|
| 1006 |
+
obel = [m for m in region if self.mon_type[m] == "obelisk" and self.mon_owner[m] == q]
|
| 1007 |
+
if not obel:
|
| 1008 |
+
return
|
| 1009 |
+
moved = set()
|
| 1010 |
+
while True:
|
| 1011 |
+
dests = sorted({j for m in obel for j in self.adj[m] if self._can_end(j, q)})
|
| 1012 |
+
srcs = [i for i in range(self.N) if self.fig_owner[i] == q and i not in moved]
|
| 1013 |
+
if not dests or not srcs:
|
| 1014 |
+
return
|
| 1015 |
+
a = yield self._dec(q, Phase.ATTUNE_SRC, [self.A_CELL + i for i in srcs] + [self.A_DONE])
|
| 1016 |
+
if a == self.A_DONE:
|
| 1017 |
+
return
|
| 1018 |
+
s = a - self.A_CELL
|
| 1019 |
+
a = yield self._dec(q, Phase.ATTUNE_DEST, [self.A_CELL + j for j in dests], src=s)
|
| 1020 |
+
d = a - self.A_CELL
|
| 1021 |
+
kind = self.fig_kind[s]
|
| 1022 |
+
self._move_fig(s, d)
|
| 1023 |
+
moved.add(d)
|
| 1024 |
+
if kind == SCORPION:
|
| 1025 |
+
yield from self._point_claws(q, d, seat=q)
|
| 1026 |
+
|
| 1027 |
+
def _underworld(self, q, region):
|
| 1028 |
+
"""Osiris perdeu a batalha: coloca ou realoca 1 token Underworld na regiao."""
|
| 1029 |
+
cells = [i for i in region if self._empty_land(i) and not self.underworld[i]]
|
| 1030 |
+
on = [i for i in range(self.N) if self.underworld[i]]
|
| 1031 |
+
if not cells or (self.uw_off[q] == 0 and not on):
|
| 1032 |
+
return
|
| 1033 |
+
src = None
|
| 1034 |
+
if self.uw_off[q] == 0:
|
| 1035 |
+
if len(on) == 1:
|
| 1036 |
+
src = on[0]
|
| 1037 |
+
else:
|
| 1038 |
+
a = yield self._dec(q, Phase.UNDERWORLD_SRC, [self.A_CELL + i for i in on] + [self.A_DONE])
|
| 1039 |
+
if a == self.A_DONE:
|
| 1040 |
+
return
|
| 1041 |
+
src = a - self.A_CELL
|
| 1042 |
+
a = yield self._dec(q, Phase.UNDERWORLD_DEST, [self.A_CELL + i for i in cells] + [self.A_DONE])
|
| 1043 |
+
if a == self.A_DONE:
|
| 1044 |
+
return
|
| 1045 |
+
if src is None:
|
| 1046 |
+
self.uw_off[q] -= 1
|
| 1047 |
+
else:
|
| 1048 |
+
self.underworld[src] = False
|
| 1049 |
+
self.underworld[a - self.A_CELL] = True
|
| 1050 |
+
|
| 1051 |
+
def _battle(self, region, players):
|
| 1052 |
+
rf = self.region_full[region]
|
| 1053 |
+
killed = [0] * self.P
|
| 1054 |
+
self.stats["battles"] += 1
|
| 1055 |
+
self.cur_region, self.cur_cards = region, None
|
| 1056 |
+
# 0. Obelisk Attuned
|
| 1057 |
+
for q in self._asc([q for q in players if OBELISK_ATT in self.powers[q]]):
|
| 1058 |
+
yield from self._attune(q, region)
|
| 1059 |
+
# 1. Amun anuncia (publico); depois escolha secreta e revelacao simultanea
|
| 1060 |
+
self.amun_declared = {}
|
| 1061 |
+
for q in players:
|
| 1062 |
+
if self._has_god(q, AMUN) and not self.amun_used and len(self.hand[q]) >= 2:
|
| 1063 |
+
a = yield self._dec(q, Phase.AMUN_DECLARE, [self.A_YESNO, self.A_YESNO + 1])
|
| 1064 |
+
if a == self.A_YESNO + 1:
|
| 1065 |
+
self.amun_declared[q] = True
|
| 1066 |
+
self.stats["amun_double"] += 1
|
| 1067 |
+
self.amun_used = True
|
| 1068 |
+
picks = {q: [] for q in players}
|
| 1069 |
+
for q in players:
|
| 1070 |
+
for _ in range(2 if self.amun_declared.get(q) else 1):
|
| 1071 |
+
avail = [c for c in sorted(self.hand[q]) if c not in picks[q]]
|
| 1072 |
+
if not avail:
|
| 1073 |
+
break
|
| 1074 |
+
a = yield self._dec(q, Phase.BATTLE_CARD, [self.A_CARD + c for c in avail])
|
| 1075 |
+
picks[q].append(a - self.A_CARD)
|
| 1076 |
+
self.pending_card[q] = list(picks[q])
|
| 1077 |
+
cards = {}
|
| 1078 |
+
for q in players:
|
| 1079 |
+
self.pending_card[q] = None
|
| 1080 |
+
cards[q] = picks[q]
|
| 1081 |
+
for c in picks[q]:
|
| 1082 |
+
self.hand[q].discard(c)
|
| 1083 |
+
self.used[q].append(c)
|
| 1084 |
+
self.stats["cards"][q][c] += 1
|
| 1085 |
+
self.cur_cards = {q: list(c) for q, c in cards.items()}
|
| 1086 |
+
protected = set()
|
| 1087 |
+
for q in players:
|
| 1088 |
+
if FLOOD in cards[q]:
|
| 1089 |
+
fert = [i for i in self._figs_in(region, q) if self._ter(i) == "F"]
|
| 1090 |
+
self.followers[q] += len(fert)
|
| 1091 |
+
protected.update(fert)
|
| 1092 |
+
# 2. Build Monument (ordem crescente de Devocao)
|
| 1093 |
+
for q in self._asc([q for q in players if BUILD in cards[q]]):
|
| 1094 |
+
yield from self._build(q, region)
|
| 1095 |
+
# 3. Plague of Locusts
|
| 1096 |
+
for _ in range(sum(1 for q in players if PLAGUE in cards[q])):
|
| 1097 |
+
yield from self._plague(region, players, killed)
|
| 1098 |
+
# 4. maiorias de monumentos
|
| 1099 |
+
maj = self._majorities(region)
|
| 1100 |
+
for q in self._asc(players):
|
| 1101 |
+
if self._figs_in(region, q) and maj[q] > 0:
|
| 1102 |
+
self.gain_dev(q, maj[q], src="maioria")
|
| 1103 |
+
# 5. resolucao
|
| 1104 |
+
nfig = {q: len(self._figs_in(region, q)) for q in players}
|
| 1105 |
+
strength = {q: self._strength(q, region, cards[q]) for q in players}
|
| 1106 |
+
cands = [q for q in players if nfig[q] > 0]
|
| 1107 |
+
winner = None
|
| 1108 |
+
if cands:
|
| 1109 |
+
top = max(strength[q] for q in cands)
|
| 1110 |
+
tops = [q for q in cands if strength[q] == top]
|
| 1111 |
+
if len(tops) == 1:
|
| 1112 |
+
winner = tops[0]
|
| 1113 |
+
elif self.tiebreak_available and self.tiebreak_holder in tops:
|
| 1114 |
+
a = yield self._dec(self.tiebreak_holder, Phase.TIEBREAK, [self.A_YESNO, self.A_YESNO + 1])
|
| 1115 |
+
if a == self.A_YESNO + 1:
|
| 1116 |
+
winner = self.tiebreak_holder
|
| 1117 |
+
self.tiebreak_available = False
|
| 1118 |
+
self.stats["tiebreak_used"] += 1
|
| 1119 |
+
prot = set(protected)
|
| 1120 |
+
for q in players: # Isis: figuras protegidas
|
| 1121 |
+
if self._has_god(q, ISIS):
|
| 1122 |
+
for i in self._figs_in(region, q):
|
| 1123 |
+
if any(self.fig_owner[j] not in (-1, q) for j in self.adjl[i]):
|
| 1124 |
+
prot.add(i)
|
| 1125 |
+
self._kill_pass([i for i in rf if self.fig_owner[i] >= 0 and self.fig_owner[i] != winner
|
| 1126 |
+
and i not in prot], killed)
|
| 1127 |
+
if winner is None:
|
| 1128 |
+
self.stats["battle_ties"] += 1
|
| 1129 |
+
else:
|
| 1130 |
+
self.stats["battle_wins"][winner] += 1
|
| 1131 |
+
for q in players:
|
| 1132 |
+
self.stats["kills"][q] += killed[q]
|
| 1133 |
+
if winner is not None:
|
| 1134 |
+
others = [strength[q] for q in players if q != winner]
|
| 1135 |
+
gap = strength[winner] - (max(others) if others else 0)
|
| 1136 |
+
gain = 3 if (GLORIOUS in self.powers[winner] and gap >= 3) else 1
|
| 1137 |
+
if DROUGHT in cards[winner]:
|
| 1138 |
+
gain += sum(1 for i in self._figs_in(region, winner) if self._ter(i) == "D")
|
| 1139 |
+
if any(self.fig_sun[i] for i in self._figs_in(region, winner)):
|
| 1140 |
+
gain += 1
|
| 1141 |
+
self.gain_dev(winner, gain, src="vitoria")
|
| 1142 |
+
if COMMANDING in self.powers[winner]:
|
| 1143 |
+
self.followers[winner] += 3
|
| 1144 |
+
for q in self._asc([q for q in players if q != winner and nfig[q] >= 2]):
|
| 1145 |
+
if MAGNANIMOUS in self.powers[q]:
|
| 1146 |
+
self.gain_dev(q, 2, src="magnanimous")
|
| 1147 |
+
self._flush_cat()
|
| 1148 |
+
for q in players: # Osiris perdeu: Underworld
|
| 1149 |
+
if q != winner and self._has_god(q, OSIRIS):
|
| 1150 |
+
yield from self._underworld(q, region)
|
| 1151 |
+
# pos-resolucao: Miracle, Worshipful, Cycle of Ma'at
|
| 1152 |
+
for q in self._asc([q for q in players if MIRACLE in cards[q]]):
|
| 1153 |
+
self.gain_dev(q, killed[q], src="miracle")
|
| 1154 |
+
for q in self._asc([q for q in players if WORSHIPFUL in self.powers[q] and cards[q]]):
|
| 1155 |
+
if self.followers[q] >= 2:
|
| 1156 |
+
a = yield self._dec(q, Phase.WORSHIP, [self.A_YESNO, self.A_YESNO + 1])
|
| 1157 |
+
if a == self.A_YESNO + 1:
|
| 1158 |
+
self.followers[q] -= 2
|
| 1159 |
+
self.gain_dev(q, 1, src="worshipful")
|
| 1160 |
+
for q in players:
|
| 1161 |
+
if CYCLE in cards[q]:
|
| 1162 |
+
self.hand[q] |= set(self.used[q])
|
| 1163 |
+
self.used[q] = []
|
| 1164 |
+
self.cur_region, self.cur_cards, self.amun_declared = None, None, {}
|
| 1165 |
+
|
| 1166 |
+
def _build(self, q, region):
|
| 1167 |
+
cost = 0 if INSPIRING in self.powers[q] else 3
|
| 1168 |
+
cells = [i for i in region if self._empty_land(i) and not self.underworld[i]]
|
| 1169 |
+
types = [t for t in range(3) if self.supply[MON_TYPES[t]] > 0]
|
| 1170 |
+
if not (self.followers[q] >= cost and self.ankh_pool[q] > 0 and cells and types):
|
| 1171 |
+
return
|
| 1172 |
+
a = yield self._dec(q, Phase.BUILD_TYPE, [self.A_BTYPE] + [self.A_BTYPE + 1 + t for t in types])
|
| 1173 |
+
t = a - self.A_BTYPE - 1
|
| 1174 |
+
if t < 0:
|
| 1175 |
+
return
|
| 1176 |
+
a = yield self._dec(q, Phase.BUILD_CELL, [self.A_CELL + i for i in cells])
|
| 1177 |
+
i = a - self.A_CELL
|
| 1178 |
+
self.stats["builds"][q] += 1
|
| 1179 |
+
self.followers[q] -= cost
|
| 1180 |
+
self.supply[MON_TYPES[t]] -= 1
|
| 1181 |
+
self.ankh_pool[q] -= 1
|
| 1182 |
+
self.mon_type[i] = MON_TYPES[t]
|
| 1183 |
+
self.mon_owner[i] = q
|
| 1184 |
+
|
| 1185 |
+
def _plague(self, region, players, killed):
|
| 1186 |
+
for q in players:
|
| 1187 |
+
top = min(self.followers[q], BID_MAX)
|
| 1188 |
+
a = yield self._dec(q, Phase.BID, [self.A_BID + k for k in range(top + 1)])
|
| 1189 |
+
self.pending_bid[q] = a - self.A_BID
|
| 1190 |
+
bids = {q: self.pending_bid[q] for q in players}
|
| 1191 |
+
self.pending_bid = [None] * self.P
|
| 1192 |
+
for q, k in bids.items():
|
| 1193 |
+
self.followers[q] -= k
|
| 1194 |
+
m = max(bids.values())
|
| 1195 |
+
top = [q for q in players if bids[q] == m]
|
| 1196 |
+
spared = top[0] if len(top) == 1 else None
|
| 1197 |
+
self._kill_pass([i for i in self.region_full[region] if self.fig_owner[i] >= 0
|
| 1198 |
+
and self.fig_owner[i] != spared and self.fig_kind[i] != GOD_K], killed)
|
| 1199 |
+
self._flush_cat()
|
ankh_map.py
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_map.py - Mapa e cenarios do Ankh em forma extensa (para editar a mao).
|
| 3 |
+
|
| 4 |
+
LAYOUT
|
| 5 |
+
------
|
| 6 |
+
Hexagonos "flat-top" organizados em COLUNAS, exatamente como no seu codigo:
|
| 7 |
+
coordenada publica = (col, linha_na_coluna), ambas a partir de 0,
|
| 8 |
+
linha_na_coluna 0 = topo da coluna.
|
| 9 |
+
As colunas ficam centralizadas na vertical, entao colunas com menos celulas
|
| 10 |
+
sao deslocadas (COLUMN_COUNTS [8,9,10,9,...] -> colunas de 9 ficam meia
|
| 11 |
+
celula abaixo das de 10; as de 8 sobram 1 celula em cima e 1 embaixo).
|
| 12 |
+
Internamente usa-se "coordenadas dobradas": r2 = 2*linha + (max - n_da_coluna).
|
| 13 |
+
|
| 14 |
+
COMO EDITAR
|
| 15 |
+
-----------
|
| 16 |
+
1) GRID_COLUMNS: uma string por coluna, uma letra por celula, de cima p/ baixo.
|
| 17 |
+
F fertil D deserto W agua
|
| 18 |
+
O tamanho de cada string define quantas celulas a coluna tem.
|
| 19 |
+
|
| 20 |
+
2) RIVER: lados com rio, como (col, linha, direcao).
|
| 21 |
+
direcoes: N, S, NE, SE, NW, SW
|
| 22 |
+
(c, r, 'SE') = rio no lado sudeste da celula (c, r), isto e, entre ela e a
|
| 23 |
+
vizinha a sudeste. Declare cada lado uma vez.
|
| 24 |
+
Confira o numero de regioes que o validador imprime: ele e o teste de que
|
| 25 |
+
o rio realmente separa (vazamento por um lado faltando e facil de cometer).
|
| 26 |
+
|
| 27 |
+
3) SCENARIOS: monumentos, figuras, camelos e Conflict Order iniciais.
|
| 28 |
+
|
| 29 |
+
Rode `python ankh_map.py` para validar e ver o mapa em ASCII.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
from collections import deque
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
|
| 36 |
+
# ---------------------------------------------------------------------------
|
| 37 |
+
# 1) GRADE POR COLUNAS (traduzida das listas water_hexes / fertile_hexes)
|
| 38 |
+
# ATENCAO: no codigo original o deserto vinha de _initialize_desert();
|
| 39 |
+
# aqui assumi "deserto = toda celula que nao e agua nem fertil".
|
| 40 |
+
# ---------------------------------------------------------------------------
|
| 41 |
+
GRID_COLUMNS = [
|
| 42 |
+
"FFDDDDDD", # col 0 (8)
|
| 43 |
+
"FFFDDDDDD", # col 1 (9)
|
| 44 |
+
"FFFFDWWDDD", # col 2 (10)
|
| 45 |
+
"FFFFDDWDD", # col 3 (9)
|
| 46 |
+
"WFFFFDWFFF", # col 4 (10)
|
| 47 |
+
"WFFFFFFFF", # col 5 (9)
|
| 48 |
+
"WFFFFFFDDD", # col 6 (10)
|
| 49 |
+
"WFFFDDDDD", # col 7 (9)
|
| 50 |
+
"WFFFDDDWDD", # col 8 (10)
|
| 51 |
+
"WFFWDDWDD", # col 9 (9)
|
| 52 |
+
"WFDWWWWW", # col 10 (8)
|
| 53 |
+
]
|
| 54 |
+
# Deslocamento vertical de cada coluna em meias celulas. None = centralizar.
|
| 55 |
+
COLUMN_OFFSET_HALF = None
|
| 56 |
+
|
| 57 |
+
# ---------------------------------------------------------------------------
|
| 58 |
+
# 2) RIOS: (col, linha, direcao) -- preencher
|
| 59 |
+
# ---------------------------------------------------------------------------
|
| 60 |
+
RIVER = [
|
| 61 |
+
(0, 0, 'NE'),
|
| 62 |
+
(0, 0, 'SE'), # estava 'E' na sua lista (nao existe em flat-top); lido como SE
|
| 63 |
+
(0, 1, 'NE'),
|
| 64 |
+
(1, 1, 'S'),
|
| 65 |
+
(2, 2, 'SW'),
|
| 66 |
+
(2, 2, 'S'),
|
| 67 |
+
(3, 2, 'SW'),
|
| 68 |
+
(3, 2, 'S'),
|
| 69 |
+
(4, 3, 'SW'),
|
| 70 |
+
(4, 3, 'S'),
|
| 71 |
+
(4, 7, 'NE'),
|
| 72 |
+
(4, 7, 'SE'),
|
| 73 |
+
(4, 8, 'NE'),
|
| 74 |
+
(4, 8, 'SE'),
|
| 75 |
+
(4, 9, 'NE'),
|
| 76 |
+
(4, 9, 'SE'), # na borda do mapa: ignorado pelo carregador
|
| 77 |
+
(5, 3, 'S'),
|
| 78 |
+
(5, 3, 'SW'),
|
| 79 |
+
(5, 3, 'SE'),
|
| 80 |
+
(5, 4, 'NE'),
|
| 81 |
+
(5, 4, 'SE'),
|
| 82 |
+
(5, 5, 'NE'),
|
| 83 |
+
(5, 5, 'SE'),
|
| 84 |
+
(5, 5, 'S'),
|
| 85 |
+
(6, 3, 'S'),
|
| 86 |
+
(6, 3, 'SE'),
|
| 87 |
+
(7, 2, 'S'),
|
| 88 |
+
(7, 2, 'SE'),
|
| 89 |
+
(8, 2, 'S'),
|
| 90 |
+
(8, 2, 'SE'),
|
| 91 |
+
(9, 1, 'S'),
|
| 92 |
+
(9, 1, 'SE'),
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
# ---------------------------------------------------------------------------
|
| 96 |
+
# 3) CENARIOS
|
| 97 |
+
# ---------------------------------------------------------------------------
|
| 98 |
+
SCENARIOS = {
|
| 99 |
+
"basic_2p": {
|
| 100 |
+
"n_players": 2,
|
| 101 |
+
# (tipo, (col, linha), dono) tipo: 'obelisk' | 'temple' | 'pyramid'
|
| 102 |
+
# dono: None (neutro) ou 0..n_players-1
|
| 103 |
+
"monuments": [
|
| 104 |
+
("obelisk", (0, 4), 0),
|
| 105 |
+
("pyramid", (1, 8), None),
|
| 106 |
+
("temple", (3, 0), None),
|
| 107 |
+
("pyramid", (5, 2), None),
|
| 108 |
+
("temple", (5, 6), 1),
|
| 109 |
+
("obelisk", (8, 1), None),
|
| 110 |
+
("pyramid", (8, 5), None),
|
| 111 |
+
],
|
| 112 |
+
# jogador -> lista de (tipo, (col, linha)) tipo: 'god' | 'warrior'
|
| 113 |
+
"figures": {
|
| 114 |
+
0: [
|
| 115 |
+
("god", (1, 5)),
|
| 116 |
+
("warrior", (1, 4)),
|
| 117 |
+
],
|
| 118 |
+
1: [
|
| 119 |
+
("god", (6, 7)),
|
| 120 |
+
("warrior", (6, 6)),
|
| 121 |
+
],
|
| 122 |
+
},
|
| 123 |
+
# lados com camelo no inicio: (col, linha, direcao)
|
| 124 |
+
"camels": [],
|
| 125 |
+
# numero do Conflict Order token -> qualquer celula (col, linha) da regiao
|
| 126 |
+
"conflict_order": {
|
| 127 |
+
1: (0, 0),
|
| 128 |
+
2: (5, 6),
|
| 129 |
+
3: (1, 0),
|
| 130 |
+
},
|
| 131 |
+
},
|
| 132 |
+
"basic_3p": {
|
| 133 |
+
"n_players": 3,
|
| 134 |
+
"monuments": [
|
| 135 |
+
("pyramid", (0, 2), None),
|
| 136 |
+
("obelisk", (2, 7), None),
|
| 137 |
+
("pyramid", (3, 1), 2),
|
| 138 |
+
("temple", (4, 5), 0),
|
| 139 |
+
("temple", (5, 3), None),
|
| 140 |
+
("obelisk", (5, 6), 1),
|
| 141 |
+
("pyramid", (7, 3), None),
|
| 142 |
+
("obelisk", (8, 1), None),
|
| 143 |
+
("temple", (9, 5), None),
|
| 144 |
+
],
|
| 145 |
+
"figures": {
|
| 146 |
+
0: [
|
| 147 |
+
("god", (3, 4)),
|
| 148 |
+
("warrior", (4, 4)),
|
| 149 |
+
],
|
| 150 |
+
1: [
|
| 151 |
+
("god", (6, 7)),
|
| 152 |
+
("warrior", (6, 6)),
|
| 153 |
+
],
|
| 154 |
+
2: [
|
| 155 |
+
("god", (4, 2)),
|
| 156 |
+
("warrior", (3, 2)),
|
| 157 |
+
],
|
| 158 |
+
},
|
| 159 |
+
"camels": [],
|
| 160 |
+
"conflict_order": {
|
| 161 |
+
1: (0, 0),
|
| 162 |
+
2: (5, 6),
|
| 163 |
+
3: (1, 0),
|
| 164 |
+
},
|
| 165 |
+
},
|
| 166 |
+
"basic_4p": {
|
| 167 |
+
"n_players": 4,
|
| 168 |
+
"monuments": [
|
| 169 |
+
("pyramid", (0, 6), None),
|
| 170 |
+
("obelisk", (1, 4), None),
|
| 171 |
+
("temple", (2, 4), 0),
|
| 172 |
+
("temple", (3, 1), None),
|
| 173 |
+
("temple", (4, 8), 1),
|
| 174 |
+
("obelisk", (5, 3), 2),
|
| 175 |
+
("pyramid", (5, 5), None),
|
| 176 |
+
("temple", (6, 8), None),
|
| 177 |
+
("pyramid", (7, 5), 3),
|
| 178 |
+
("pyramid", (8, 2), None),
|
| 179 |
+
("obelisk", (8, 3), None),
|
| 180 |
+
],
|
| 181 |
+
"figures": {
|
| 182 |
+
0: [
|
| 183 |
+
("god", (1, 3)),
|
| 184 |
+
("warrior", (2, 3)),
|
| 185 |
+
],
|
| 186 |
+
1: [
|
| 187 |
+
("god", (3, 7)),
|
| 188 |
+
("warrior", (4, 7)),
|
| 189 |
+
],
|
| 190 |
+
2: [
|
| 191 |
+
("god", (5, 2)),
|
| 192 |
+
("warrior", (4, 3)),
|
| 193 |
+
],
|
| 194 |
+
3: [
|
| 195 |
+
("god", (7, 4)),
|
| 196 |
+
("warrior", (6, 5)),
|
| 197 |
+
],
|
| 198 |
+
},
|
| 199 |
+
"camels": [(0, 2, "S"),
|
| 200 |
+
(1, 3, "SW"),
|
| 201 |
+
(1, 3, "S"),
|
| 202 |
+
(2, 4, "SW"),
|
| 203 |
+
],
|
| 204 |
+
"conflict_order": {
|
| 205 |
+
1: (0, 0),
|
| 206 |
+
2: (0, 3),
|
| 207 |
+
3: (1, 0),
|
| 208 |
+
4: (5, 6),
|
| 209 |
+
},
|
| 210 |
+
},
|
| 211 |
+
"basic_5p": {
|
| 212 |
+
"n_players": 5,
|
| 213 |
+
"monuments": [
|
| 214 |
+
("temple", (1, 2), 0),
|
| 215 |
+
("obelisk", (1, 4), None),
|
| 216 |
+
("pyramid", (1, 7), 4),
|
| 217 |
+
("obelisk", (2, 0), None),
|
| 218 |
+
("temple", (4, 8), None),
|
| 219 |
+
("pyramid", (5, 3), 3),
|
| 220 |
+
("pyramid", (5, 4), None),
|
| 221 |
+
("temple", (6, 1), None),
|
| 222 |
+
("pyramid", (6, 6), None),
|
| 223 |
+
("obelisk", (6, 7), None),
|
| 224 |
+
("obelisk", (8, 3), 1),
|
| 225 |
+
("temple", (8, 9), 2),
|
| 226 |
+
],
|
| 227 |
+
"figures": {
|
| 228 |
+
0: [
|
| 229 |
+
("god", (1, 3)),
|
| 230 |
+
("warrior", (2, 3)),
|
| 231 |
+
],
|
| 232 |
+
1: [
|
| 233 |
+
("god", (8, 4)),
|
| 234 |
+
("warrior", (7, 3)),
|
| 235 |
+
],
|
| 236 |
+
2: [
|
| 237 |
+
("god", (8, 8)),
|
| 238 |
+
("warrior", (7, 8)),
|
| 239 |
+
],
|
| 240 |
+
3: [
|
| 241 |
+
("god", (4, 3)),
|
| 242 |
+
("warrior", (5, 2)),
|
| 243 |
+
],
|
| 244 |
+
4: [
|
| 245 |
+
("god", (1, 6)),
|
| 246 |
+
("warrior", (2, 7)),
|
| 247 |
+
],
|
| 248 |
+
},
|
| 249 |
+
"camels": [(0, 2, "S"),
|
| 250 |
+
(1, 3, "SW"),
|
| 251 |
+
(1, 3, "S"),
|
| 252 |
+
(2, 4, "SW"),
|
| 253 |
+
(5, 6, "S"),
|
| 254 |
+
(5, 6, "SE"),
|
| 255 |
+
(6, 6, "S"),
|
| 256 |
+
(6, 6, "SE"),
|
| 257 |
+
(7, 5, "S"),
|
| 258 |
+
(8, 6, "SW"),
|
| 259 |
+
],
|
| 260 |
+
"conflict_order": {
|
| 261 |
+
1: (0, 0),
|
| 262 |
+
2: (5, 6),
|
| 263 |
+
3: (5, 7),
|
| 264 |
+
4: (1, 0),
|
| 265 |
+
5: (0, 3),
|
| 266 |
+
},
|
| 267 |
+
},
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
# ===========================================================================
|
| 271 |
+
# Geometria (flat-top, coordenadas dobradas internamente)
|
| 272 |
+
# ===========================================================================
|
| 273 |
+
AXIAL_DIRS = [(1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1)]
|
| 274 |
+
|
| 275 |
+
# (d_r2, d_col) em coordenadas dobradas
|
| 276 |
+
_DELTA = {"N": (-2, 0), "S": (2, 0), "NE": (-1, 1), "SE": (1, 1), "NW": (-1, -1), "SW": (1, -1)}
|
| 277 |
+
DIRECTIONS = tuple(_DELTA)
|
| 278 |
+
TERRAIN_CHARS = {"F", "D", "W"}
|
| 279 |
+
MONUMENT_TYPES = {"obelisk", "temple", "pyramid"}
|
| 280 |
+
FIGURE_TYPES = {"god", "warrior"}
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def nbrs(ax):
|
| 284 |
+
"""Vizinhas em coordenadas axiais (funciona tambem fora do mapa)."""
|
| 285 |
+
return {(ax[0] + dq, ax[1] + dr) for dq, dr in AXIAL_DIRS}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def edge(a, b):
|
| 289 |
+
"""Lado de hexagono entre duas celulas (coordenadas axiais)."""
|
| 290 |
+
return frozenset((a, b))
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def components(land, blocked_edges):
|
| 294 |
+
"""Regioes: componentes conexos de celulas de terra, sem cruzar rio/camelo."""
|
| 295 |
+
seen, comps = set(), []
|
| 296 |
+
for s in land:
|
| 297 |
+
if s in seen:
|
| 298 |
+
continue
|
| 299 |
+
stack, comp = [s], {s}
|
| 300 |
+
seen.add(s)
|
| 301 |
+
while stack:
|
| 302 |
+
u = stack.pop()
|
| 303 |
+
for v in nbrs(u) & land:
|
| 304 |
+
if v not in seen and edge(u, v) not in blocked_edges:
|
| 305 |
+
seen.add(v)
|
| 306 |
+
comp.add(v)
|
| 307 |
+
stack.append(v)
|
| 308 |
+
comps.append(frozenset(comp))
|
| 309 |
+
return comps
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# ===========================================================================
|
| 313 |
+
# Tabuleiro
|
| 314 |
+
# ===========================================================================
|
| 315 |
+
class Board:
|
| 316 |
+
"""Estrutura estatica do tabuleiro.
|
| 317 |
+
|
| 318 |
+
terrain dict (col,linha) -> 'F'|'D'|'W'
|
| 319 |
+
cells lista ordenada de (col,linha); indice = id da celula
|
| 320 |
+
idx dict (col,linha) -> indice
|
| 321 |
+
land, water conjuntos de coords AXIAIS (para regioes e camelos)
|
| 322 |
+
river_edges frozenset de lados (frozenset de 2 coords axiais)
|
| 323 |
+
move_dist np.int8 [N,N]: distancia de movimento (atravessa tudo no mapa)
|
| 324 |
+
axial(rc) (col,linha) -> coord axial
|
| 325 |
+
step(rc, d) vizinha de rc na direcao d, ou None se fora do mapa
|
| 326 |
+
"""
|
| 327 |
+
|
| 328 |
+
def __init__(self, grid_columns, offsets_half, river, warnings):
|
| 329 |
+
self.counts = [len(s) for s in grid_columns]
|
| 330 |
+
self.ncols = len(grid_columns)
|
| 331 |
+
self.warnings = warnings
|
| 332 |
+
self.terrain = {}
|
| 333 |
+
self._pos, self._inv = {}, {}
|
| 334 |
+
for c, col in enumerate(grid_columns):
|
| 335 |
+
for r, ch in enumerate(col):
|
| 336 |
+
if ch not in TERRAIN_CHARS:
|
| 337 |
+
raise ValueError(f"caractere invalido {ch!r} em {(c, r)}")
|
| 338 |
+
r2 = 2 * r + offsets_half[c]
|
| 339 |
+
if (r2 + c) % 2:
|
| 340 |
+
raise ValueError(
|
| 341 |
+
f"coluna {c}: deslocamento incompativel (paridade); "
|
| 342 |
+
"colunas vizinhas precisam alternar meia celula")
|
| 343 |
+
self.terrain[(c, r)] = ch
|
| 344 |
+
self._pos[(c, r)] = (r2, c)
|
| 345 |
+
self._inv[(r2, c)] = (c, r)
|
| 346 |
+
self.max_r2 = max(p[0] for p in self._pos.values())
|
| 347 |
+
self.cells = sorted(self.terrain)
|
| 348 |
+
self.idx = {rc: i for i, rc in enumerate(self.cells)}
|
| 349 |
+
self.land = {self.axial(rc) for rc, t in self.terrain.items() if t != "W"}
|
| 350 |
+
self.water = {self.axial(rc) for rc, t in self.terrain.items() if t == "W"}
|
| 351 |
+
|
| 352 |
+
edges = set()
|
| 353 |
+
for (c, r, d) in river:
|
| 354 |
+
if d not in DIRECTIONS:
|
| 355 |
+
raise ValueError(f"direcao invalida {d!r} em rio {(c, r, d)}")
|
| 356 |
+
a, b = (c, r), self.step((c, r), d)
|
| 357 |
+
if a not in self.terrain:
|
| 358 |
+
raise ValueError(f"rio {(c, r, d)}: celula {a} nao existe")
|
| 359 |
+
if b is None:
|
| 360 |
+
# lado na borda do mapa: nao separa nada, so ignorar
|
| 361 |
+
warnings.append(f"rio {(c, r, d)} fica na borda do mapa (ignorado)")
|
| 362 |
+
continue
|
| 363 |
+
if "W" in (self.terrain[a], self.terrain[b]):
|
| 364 |
+
warnings.append(f"rio {(c, r, d)} toca agua; rios normalmente separam terra de terra")
|
| 365 |
+
edges.add(edge(self.axial(a), self.axial(b)))
|
| 366 |
+
self.river_edges = frozenset(edges)
|
| 367 |
+
self.move_dist = self._distances()
|
| 368 |
+
|
| 369 |
+
def axial(self, rc):
|
| 370 |
+
r2, c = self._pos[rc]
|
| 371 |
+
return (c, (r2 - c) // 2)
|
| 372 |
+
|
| 373 |
+
def step(self, rc, d):
|
| 374 |
+
r2, c = self._pos[rc]
|
| 375 |
+
dr, dc = _DELTA[d]
|
| 376 |
+
return self._inv.get((r2 + dr, c + dc))
|
| 377 |
+
|
| 378 |
+
def _distances(self):
|
| 379 |
+
n = len(self.cells)
|
| 380 |
+
dist = np.full((n, n), 99, dtype=np.int8)
|
| 381 |
+
for s in range(n):
|
| 382 |
+
dist[s, s] = 0
|
| 383 |
+
q = deque([self.cells[s]])
|
| 384 |
+
while q:
|
| 385 |
+
u = q.popleft()
|
| 386 |
+
du = dist[s, self.idx[u]]
|
| 387 |
+
for d in DIRECTIONS:
|
| 388 |
+
v = self.step(u, d)
|
| 389 |
+
if v is not None and dist[s, self.idx[v]] == 99:
|
| 390 |
+
dist[s, self.idx[v]] = du + 1
|
| 391 |
+
q.append(v)
|
| 392 |
+
return dist
|
| 393 |
+
|
| 394 |
+
def selfcheck(self):
|
| 395 |
+
"""Vizinhas por direcao == vizinhas axiais (garante a geometria)."""
|
| 396 |
+
for rc in self.cells:
|
| 397 |
+
got = {self.axial(v) for v in (self.step(rc, d) for d in DIRECTIONS) if v}
|
| 398 |
+
want = nbrs(self.axial(rc)) & {self.axial(x) for x in self.cells}
|
| 399 |
+
assert got == want, f"geometria inconsistente em {rc}"
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def build_board(grid_columns=None, river=None, offsets_half=None):
|
| 403 |
+
grid_columns = GRID_COLUMNS if grid_columns is None else grid_columns
|
| 404 |
+
river = RIVER if river is None else river
|
| 405 |
+
offsets_half = COLUMN_OFFSET_HALF if offsets_half is None else offsets_half
|
| 406 |
+
if not grid_columns or not any(grid_columns):
|
| 407 |
+
raise ValueError("GRID_COLUMNS vazio")
|
| 408 |
+
if offsets_half is None:
|
| 409 |
+
m = max(len(s) for s in grid_columns)
|
| 410 |
+
offsets_half = [m - len(s) for s in grid_columns]
|
| 411 |
+
return Board(grid_columns, offsets_half, river, [])
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
# ===========================================================================
|
| 415 |
+
# Cenario
|
| 416 |
+
# ===========================================================================
|
| 417 |
+
class Setup:
|
| 418 |
+
"""Estado inicial validado.
|
| 419 |
+
|
| 420 |
+
monuments : lista de (tipo, (col,linha), dono)
|
| 421 |
+
figures : dict jogador -> lista de (tipo, (col,linha))
|
| 422 |
+
camel_edges: frozenset de lados (axiais)
|
| 423 |
+
regions : lista de frozensets de coords axiais
|
| 424 |
+
region_of : dict coord axial -> indice da regiao
|
| 425 |
+
conflict_order: dict indice da regiao -> numero do token
|
| 426 |
+
errors : lista de mensagens de erro
|
| 427 |
+
"""
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def load_scenario(board, sc):
|
| 431 |
+
errors = []
|
| 432 |
+
n_players = sc["n_players"]
|
| 433 |
+
|
| 434 |
+
camel_edges = set()
|
| 435 |
+
for (c, r, d) in sc.get("camels", []):
|
| 436 |
+
a, b = (c, r), board.step((c, r), d) if (c, r) in board.terrain else None
|
| 437 |
+
if b is None or "W" in (board.terrain[a], board.terrain[b]):
|
| 438 |
+
errors.append(f"camelo {(c, r, d)} deve ficar entre duas celulas de terra")
|
| 439 |
+
continue
|
| 440 |
+
camel_edges.add(edge(board.axial(a), board.axial(b)))
|
| 441 |
+
|
| 442 |
+
regions = components(board.land, board.river_edges | camel_edges)
|
| 443 |
+
region_of = {ax: i for i, comp in enumerate(regions) for ax in comp}
|
| 444 |
+
|
| 445 |
+
occupied = {}
|
| 446 |
+
|
| 447 |
+
def occupy(rc, what):
|
| 448 |
+
if rc not in board.terrain:
|
| 449 |
+
errors.append(f"{what} em {rc}: fora do mapa")
|
| 450 |
+
elif board.terrain[rc] == "W":
|
| 451 |
+
errors.append(f"{what} em {rc}: celula de agua")
|
| 452 |
+
elif rc in occupied:
|
| 453 |
+
errors.append(f"{what} em {rc}: ja ocupada por {occupied[rc]}")
|
| 454 |
+
else:
|
| 455 |
+
occupied[rc] = what
|
| 456 |
+
|
| 457 |
+
monuments = []
|
| 458 |
+
for (kind, rc, owner) in sc.get("monuments", []):
|
| 459 |
+
if kind not in MONUMENT_TYPES:
|
| 460 |
+
errors.append(f"tipo de monumento invalido {kind!r}")
|
| 461 |
+
if owner is not None and not (0 <= owner < n_players):
|
| 462 |
+
errors.append(f"dono invalido {owner} no monumento em {rc}")
|
| 463 |
+
occupy(rc, f"monumento {kind}")
|
| 464 |
+
monuments.append((kind, rc, owner))
|
| 465 |
+
|
| 466 |
+
figures = {}
|
| 467 |
+
for p, figs in sc.get("figures", {}).items():
|
| 468 |
+
if not (0 <= p < n_players):
|
| 469 |
+
errors.append(f"jogador invalido {p} em figures")
|
| 470 |
+
continue
|
| 471 |
+
figures[p] = list(figs)
|
| 472 |
+
n_god = sum(1 for k, _ in figs if k == "god")
|
| 473 |
+
n_war = sum(1 for k, _ in figs if k == "warrior")
|
| 474 |
+
if n_god > 1:
|
| 475 |
+
errors.append(f"jogador {p} tem {n_god} deuses")
|
| 476 |
+
if n_war > 6:
|
| 477 |
+
errors.append(f"jogador {p} tem {n_war} guerreiros (max 6)")
|
| 478 |
+
for kind, rc in figs:
|
| 479 |
+
if kind not in FIGURE_TYPES:
|
| 480 |
+
errors.append(f"tipo de figura invalido {kind!r}")
|
| 481 |
+
occupy(rc, f"figura {kind} do jogador {p}")
|
| 482 |
+
|
| 483 |
+
conflict_order = {}
|
| 484 |
+
tokens = sc.get("conflict_order", {})
|
| 485 |
+
for token, rc in tokens.items():
|
| 486 |
+
if rc not in board.terrain or board.terrain[rc] == "W":
|
| 487 |
+
errors.append(f"token {token} em {rc}: nao e celula de terra")
|
| 488 |
+
continue
|
| 489 |
+
ri = region_of[board.axial(rc)]
|
| 490 |
+
if ri in conflict_order:
|
| 491 |
+
errors.append(f"regiao de {rc} recebeu mais de um token")
|
| 492 |
+
conflict_order[ri] = token
|
| 493 |
+
missing = [i for i in range(len(regions)) if i not in conflict_order]
|
| 494 |
+
if missing:
|
| 495 |
+
errors.append(f"regioes sem Conflict Order token: {missing}")
|
| 496 |
+
|
| 497 |
+
s = Setup()
|
| 498 |
+
s.monuments, s.figures = monuments, figures
|
| 499 |
+
s.camel_edges, s.regions, s.region_of = frozenset(camel_edges), regions, region_of
|
| 500 |
+
s.conflict_order, s.errors = conflict_order, errors
|
| 501 |
+
return s
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
# ===========================================================================
|
| 505 |
+
# Visualizacao ASCII
|
| 506 |
+
# ===========================================================================
|
| 507 |
+
def render(board, setup=None, show_regions=False, labels=False):
|
| 508 |
+
"""Mapa em layout escalonado (uma linha de texto por meia celula).
|
| 509 |
+
|
| 510 |
+
Cada celula ocupa 4 colunas: terreno, simbolo, dono. Ex.: 'FT0 '.
|
| 511 |
+
Simbolos: O/T/P = obelisco/templo/piramide (dono '-' = neutro);
|
| 512 |
+
g/w = deus/guerreiro (dono = jogador).
|
| 513 |
+
labels=True mostra 'col:linha' de cada celula (util para escrever rios).
|
| 514 |
+
show_regions=True troca o terreno pela letra da regiao."""
|
| 515 |
+
overlay = {}
|
| 516 |
+
if setup is not None:
|
| 517 |
+
for kind, rc, owner in setup.monuments:
|
| 518 |
+
overlay[rc] = kind[0].upper() + ("-" if owner is None else str(owner))
|
| 519 |
+
for p, figs in setup.figures.items():
|
| 520 |
+
for kind, rc in figs:
|
| 521 |
+
overlay[rc] = ("g" if kind == "god" else "w") + str(p)
|
| 522 |
+
w = 6 if labels else 4
|
| 523 |
+
out = [" " + "".join(f"{c:<{w}d}" for c in range(board.ncols))]
|
| 524 |
+
for r2 in range(board.max_r2 + 1):
|
| 525 |
+
line = f"{r2 / 2:>4.1f} "
|
| 526 |
+
for c in range(board.ncols):
|
| 527 |
+
rc = board._inv.get((r2, c))
|
| 528 |
+
if rc is None:
|
| 529 |
+
line += " " * w
|
| 530 |
+
elif labels:
|
| 531 |
+
line += f"{rc[0]}:{rc[1]}".ljust(w)
|
| 532 |
+
else:
|
| 533 |
+
ch = board.terrain[rc]
|
| 534 |
+
if show_regions and setup is not None and ch != "W":
|
| 535 |
+
ch = chr(ord("A") + setup.region_of[board.axial(rc)] % 26)
|
| 536 |
+
line += ch + overlay.get(rc, " ") + " "
|
| 537 |
+
out.append(line.rstrip())
|
| 538 |
+
return "\n".join(out)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def validate_all(verbose=True):
|
| 542 |
+
try:
|
| 543 |
+
board = build_board()
|
| 544 |
+
board.selfcheck()
|
| 545 |
+
except (ValueError, AssertionError) as e:
|
| 546 |
+
print("ERRO:", e)
|
| 547 |
+
return False
|
| 548 |
+
for w in board.warnings:
|
| 549 |
+
print("AVISO:", w)
|
| 550 |
+
n_land, n_water = len(board.land), len(board.water)
|
| 551 |
+
print(f"{len(board.cells)} celulas ({n_land} terra, {n_water} agua); "
|
| 552 |
+
f"{len(board.river_edges)} lados de rio")
|
| 553 |
+
ok = True
|
| 554 |
+
for name, sc in SCENARIOS.items():
|
| 555 |
+
setup = load_scenario(board, sc)
|
| 556 |
+
sizes = sorted((len(r) for r in setup.regions), reverse=True)
|
| 557 |
+
if verbose:
|
| 558 |
+
print(f"\n=== {name} ===")
|
| 559 |
+
print(f"{len(setup.regions)} regioes, tamanhos (so terra): {sizes}")
|
| 560 |
+
print(render(board, setup))
|
| 561 |
+
print("\nRegioes:")
|
| 562 |
+
print(render(board, setup, show_regions=True))
|
| 563 |
+
for e in setup.errors:
|
| 564 |
+
print("ERRO:", e)
|
| 565 |
+
ok = False
|
| 566 |
+
return ok
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
if __name__ == "__main__":
|
| 570 |
+
raise SystemExit(0 if validate_all() else 1)
|
ankh_obs.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_obs.py - Codificacao da observacao (do ponto de vista de um jogador).
|
| 3 |
+
|
| 4 |
+
NAO le g.pending_card nem g.pending_bid: escolhas secretas ainda nao reveladas
|
| 5 |
+
nunca vazam para o adversario. Cartas reveladas (g.cur_cards), cartas usadas,
|
| 6 |
+
poderes desbloqueados, deuses e Guardioes sao publicos, como no jogo.
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from ankh_game import (K_LINES, MON_TYPES, EVENTS, ACTION_START, TOP, RED_SPACES, Phase, N_TOKENS,
|
| 11 |
+
N_POWERS, N_GODS, GUARDIAN_KINDS, GUARDIAN_CARDS, ANUBIS_SLOTS, CYCLIC)
|
| 12 |
+
from ankh_map import DIRECTIONS, edge, components
|
| 13 |
+
|
| 14 |
+
N_CELL_CH = 48 # 44 em uso + 4 reservados
|
| 15 |
+
MAX_OPP = 4 # oponentes visiveis (2 a 5 jogadores)
|
| 16 |
+
ENT_FEATS = 17 + N_POWERS + 2 * N_GODS + 7 + 7 + 6 + 6 # features por entidade (sem a mao)
|
| 17 |
+
LINE_FEATS = 11
|
| 18 |
+
N_PHASES = len(Phase)
|
| 19 |
+
EVENT_KINDS = ["ctrl", "camel", "conf", "end"]
|
| 20 |
+
N_RESERVED_GLOBALS = 24
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Encoder:
|
| 24 |
+
def __init__(self, g):
|
| 25 |
+
self.g = g
|
| 26 |
+
b = g.board
|
| 27 |
+
N = g.N
|
| 28 |
+
self.dir_nb = [[(b.idx[b.step(rc, d)] if b.step(rc, d) is not None else -1)
|
| 29 |
+
for d in DIRECTIONS] for rc in b.cells]
|
| 30 |
+
self.terr = np.zeros((N, 3), np.float32)
|
| 31 |
+
for i, t in enumerate(g.terrain):
|
| 32 |
+
self.terr[i, "FDW".index(t)] = 1
|
| 33 |
+
self._blk_key = None
|
| 34 |
+
self._flags = np.zeros((N, 6), np.float32)
|
| 35 |
+
|
| 36 |
+
def _blocked_flags(self):
|
| 37 |
+
g = self.g
|
| 38 |
+
key = frozenset(g.camel_edges)
|
| 39 |
+
if key != self._blk_key:
|
| 40 |
+
blocked = g.board.river_edges | g.camel_edges
|
| 41 |
+
f = np.zeros((g.N, 6), np.float32)
|
| 42 |
+
for i in range(g.N):
|
| 43 |
+
if not g.is_land[i]:
|
| 44 |
+
continue
|
| 45 |
+
for d, j in enumerate(self.dir_nb[i]):
|
| 46 |
+
if j >= 0 and g.is_land[j] and edge(g.ax[i], g.ax[j]) in blocked:
|
| 47 |
+
f[i, d] = 1
|
| 48 |
+
self._flags, self._blk_key = f, key
|
| 49 |
+
return self._flags
|
| 50 |
+
|
| 51 |
+
def line_feats(self, dec, me):
|
| 52 |
+
g = self.g
|
| 53 |
+
out = np.zeros((K_LINES, LINE_FEATS), np.float32)
|
| 54 |
+
lines = dec.info.get("lines") if dec.phase == Phase.CAMEL_LINE else None
|
| 55 |
+
if not lines:
|
| 56 |
+
return out
|
| 57 |
+
blocked = g.board.river_edges | g.camel_edges
|
| 58 |
+
reg_ax = {r: frozenset(g.ax[i] for i in r) for r in g.regions}
|
| 59 |
+
for k, line in enumerate(lines[:K_LINES]):
|
| 60 |
+
a = next(iter(next(iter(line))))
|
| 61 |
+
parts = components(reg_ax[g.region_of[g.ax2i[a]]], blocked | line)
|
| 62 |
+
out[k, 0] = len(line) / 6
|
| 63 |
+
col = 1
|
| 64 |
+
for part in sorted(parts, key=len):
|
| 65 |
+
idx = [g.ax2i[x] for x in part]
|
| 66 |
+
own = sum(g.fig_owner[i] == me for i in idx)
|
| 67 |
+
en = sum(g.fig_owner[i] not in (-1, me) for i in idx)
|
| 68 |
+
om = sum(g.mon_type[i] is not None and g.mon_owner[i] == me for i in idx)
|
| 69 |
+
em = sum(g.mon_type[i] is not None and g.mon_owner[i] not in (-1, me) for i in idx)
|
| 70 |
+
out[k, col:col + 5] = [len(idx) / 40, own / 7, en / 7, om / 3, em / 3]
|
| 71 |
+
col += 5
|
| 72 |
+
return out
|
| 73 |
+
|
| 74 |
+
def encode(self, dec):
|
| 75 |
+
"""Observacao do assento dec.player: 'eu' = a entidade que ele controla; ate 4 oponentes
|
| 76 |
+
(entidades), ordenados pela ordem de turno a partir de mim, com zeros nos espacos vazios."""
|
| 77 |
+
g = self.g
|
| 78 |
+
seat = dec.player
|
| 79 |
+
me = g.rep[seat]
|
| 80 |
+
N = g.N
|
| 81 |
+
opps = []
|
| 82 |
+
for k in range(1, g.P):
|
| 83 |
+
e = g.rep[(seat + k) % g.P]
|
| 84 |
+
if e != me and e not in opps:
|
| 85 |
+
opps.append(e)
|
| 86 |
+
opps = opps[:MAX_OPP]
|
| 87 |
+
slot = {e: k for k, e in enumerate(opps)}
|
| 88 |
+
|
| 89 |
+
c = np.zeros((N, N_CELL_CH), np.float32)
|
| 90 |
+
c[:, 0:3] = self.terr
|
| 91 |
+
for i in range(N):
|
| 92 |
+
ow = g.fig_owner[i]
|
| 93 |
+
if ow >= 0:
|
| 94 |
+
if ow == me:
|
| 95 |
+
c[i, 3 + g.fig_kind[i] - 1] = 1
|
| 96 |
+
else:
|
| 97 |
+
c[i, 11 + g.fig_kind[i] - 1] = 1
|
| 98 |
+
c[i, 19 + slot.get(ow, 0)] = 1
|
| 99 |
+
if g.claw[i] is not None: # alvos das garras do Scorpion
|
| 100 |
+
for d in (g.claw[i], (g.claw[i] + 1) % 6):
|
| 101 |
+
j = g.cyc_nb[i][d]
|
| 102 |
+
if j >= 0:
|
| 103 |
+
c[j, 42 if ow == me else 43] = 1
|
| 104 |
+
if g.fig_sun[i]:
|
| 105 |
+
c[i, 41] = 1
|
| 106 |
+
t = g.mon_type[i]
|
| 107 |
+
if t is not None:
|
| 108 |
+
c[i, 23 + MON_TYPES.index(t)] = 1
|
| 109 |
+
mo = g.mon_owner[i]
|
| 110 |
+
c[i, 26 + (0 if mo == -1 else 1 if mo == me else 2 + slot.get(mo, 0))] = 1
|
| 111 |
+
if g.underworld[i]:
|
| 112 |
+
c[i, 40] = 1
|
| 113 |
+
for r, tok in g.tokens.items():
|
| 114 |
+
for i in r:
|
| 115 |
+
c[i, 32] = tok / N_TOKENS
|
| 116 |
+
c[:, 33:39] = self._blocked_flags()
|
| 117 |
+
if g.cur_region is not None:
|
| 118 |
+
for i in g.cur_region:
|
| 119 |
+
c[i, 39] = 1
|
| 120 |
+
|
| 121 |
+
alive_ents = sorted((e for e in range(g.P) if g.rep[e] == e and g.alive[e]), key=g.dev_key)
|
| 122 |
+
rc = g.cur_cards or {}
|
| 123 |
+
|
| 124 |
+
def ent(e, mine):
|
| 125 |
+
if e is None:
|
| 126 |
+
return [0.0] * (ENT_FEATS + (7 if mine else 0))
|
| 127 |
+
rank = alive_ents.index(e) / max(len(alive_ents) - 1, 1) if e in alive_ents else 0.0
|
| 128 |
+
f = [min(g.followers[e], 10) / 10, g.warriors_pool[e] / 6, g.ankh_pool[e] / 9, g.dev_pos[e] / TOP,
|
| 129 |
+
rank, float(g.dev_pos[e] >= RED_SPACES), float(g.alive[e]), g.unlock_next[e] / 6,
|
| 130 |
+
g.sun_left[e] / 3, g.uw_off[e] / 3, len(g.trapped[e]) / ANUBIS_SLOTS,
|
| 131 |
+
sum(t.count(e) for t in g.trapped) / ANUBIS_SLOTS, g.bases_used["small"][e] / 2,
|
| 132 |
+
g.bases_used["large"][e] / 2, len(g.hand[e]) / 7, float(g.amun_declared.get(e, False)),
|
| 133 |
+
float(g.merged is not None and g.merged[0] == e)]
|
| 134 |
+
f += [float(k in g.powers[e]) for k in range(N_POWERS)]
|
| 135 |
+
f += [float(g.god[e] == k) for k in range(N_GODS)]
|
| 136 |
+
f += [float(g.god2[e] == k) for k in range(N_GODS)]
|
| 137 |
+
f += [float(k in g.used[e]) for k in range(7)]
|
| 138 |
+
f += [float(k in rc.get(e, [])) for k in range(7)]
|
| 139 |
+
f += [float(g.gpool[e].count(k)) for k in GUARDIAN_KINDS]
|
| 140 |
+
f += [sum(1 for i in range(N) if g.fig_kind[i] == k and g.fig_owner[i] == e) / 2 for k in GUARDIAN_KINDS]
|
| 141 |
+
if mine:
|
| 142 |
+
f += [float(k in g.hand[e]) for k in range(7)]
|
| 143 |
+
return f
|
| 144 |
+
|
| 145 |
+
gl = ent(me, True)
|
| 146 |
+
for k in range(MAX_OPP):
|
| 147 |
+
gl += ent(opps[k] if k < len(opps) else None, False)
|
| 148 |
+
gl += [float(g.P == p) for p in (2, 3, 4, 5)]
|
| 149 |
+
gl += [float(g.merged is not None), float(g.merged is not None and g.merged[0] == me)]
|
| 150 |
+
gl += [seat / max(g.P - 1, 1), ((g.cur - seat) % g.P) / g.P, float(g.cur == seat)]
|
| 151 |
+
start = ACTION_START[g.P]
|
| 152 |
+
gl += [(m - start) / (6 - start) for m in g.markers]
|
| 153 |
+
nxt = EVENTS[g.event_idx] if g.event_idx < len(EVENTS) else "end"
|
| 154 |
+
gl += [float(nxt == k) for k in EVENT_KINDS]
|
| 155 |
+
gl += [g.event_idx / len(EVENTS), g.conflicts_done / 5]
|
| 156 |
+
gl += [float(g.tiebreak_available), float(g.tiebreak_holder == me), float(g.amun_used)]
|
| 157 |
+
gl += [g.supply[t] / 10 for t in MON_TYPES]
|
| 158 |
+
gl += [g.camel_supply / 30, len(g.regions) / 8]
|
| 159 |
+
tf = g.turn_first
|
| 160 |
+
gl += [float(tf is None)] + [float(tf == k) for k in range(4)]
|
| 161 |
+
for lvl in (1, 2, 3):
|
| 162 |
+
gl += [float(g.g_card[lvl] == GUARDIAN_CARDS[lvl][0]), float(g.g_card[lvl] == GUARDIAN_CARDS[lvl][1]),
|
| 163 |
+
g.g_supply[lvl] / 3]
|
| 164 |
+
gl += [0.0] * N_RESERVED_GLOBALS
|
| 165 |
+
ph = np.zeros(N_PHASES, np.float32)
|
| 166 |
+
ph[int(dec.phase)] = 1
|
| 167 |
+
ctx = np.zeros(N, np.float32)
|
| 168 |
+
if "src" in dec.info and dec.phase in (Phase.MOVE_DEST, Phase.PUSH_DEST, Phase.ATTUNE_DEST, Phase.CLAW_POINT):
|
| 169 |
+
ctx[dec.info["src"]] = 1
|
| 170 |
+
v = np.concatenate([c.ravel(), np.asarray(gl, np.float32), ph, ctx,
|
| 171 |
+
self.line_feats(dec, me).ravel()])
|
| 172 |
+
return np.clip(v, 0.0, 1.0)
|
| 173 |
+
|
| 174 |
+
@staticmethod
|
| 175 |
+
def potential(g, me):
|
| 176 |
+
"""Phi(s) do shaping potencial: vantagem de Devocao + progresso ate sair do vermelho."""
|
| 177 |
+
others = [g.dev_pos[e] for e in range(g.P) if e != me and g.rep[e] == e]
|
| 178 |
+
return ((g.dev_pos[me] - (max(others) if others else 0)) / TOP
|
| 179 |
+
+ min(g.dev_pos[me], RED_SPACES) / RED_SPACES)
|
ankh_report.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_report.py - Estatisticas detalhadas por partida, por round e relatorio em Markdown.
|
| 3 |
+
|
| 4 |
+
Agg acumula resumos de partidas (AnkhGame.summary, do ponto de vista do agente)
|
| 5 |
+
make_stats_callback callback do SB3: agrega as partidas de TREINO e grava escalares no TensorBoard
|
| 6 |
+
log_round acrescenta o registro de um round em report.jsonl
|
| 7 |
+
render_markdown gera relatorio.md a partir de report.jsonl (e curvas.png se houver matplotlib)
|
| 8 |
+
|
| 9 |
+
Tudo sem dependencias pesadas no import (o SB3 so e importado em make_stats_callback).
|
| 10 |
+
"""
|
| 11 |
+
import collections
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
from ankh_game import GODS, GUARDIAN_KINDS, KIND_NAMES, POWER_NAMES
|
| 16 |
+
|
| 17 |
+
ACTION_NAMES = ["mover", "invocar", "seguidores", "desbloquear"]
|
| 18 |
+
CARD_NAMES_PT = ["plague", "build", "chariots", "cycle", "drought", "flood", "miracle"]
|
| 19 |
+
END_NAMES = {"topo": "chegou ao topo da Devocao", "ultimo_deus": "unico deus apos o 4o Conflito",
|
| 20 |
+
"ultimo_evento": "maior Devocao no ultimo evento", "egito_ateu": "Egito ateu (todos esquecidos)"}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Agg:
|
| 24 |
+
"""Acumulador de resumos de partida (cada resumo e do ponto de vista do agente)."""
|
| 25 |
+
|
| 26 |
+
def __init__(self):
|
| 27 |
+
self.n = 0
|
| 28 |
+
self.c = collections.Counter()
|
| 29 |
+
self.end = collections.Counter()
|
| 30 |
+
self.dev_src = [collections.Counter(), collections.Counter()]
|
| 31 |
+
self.cards = [[0] * 7, [0] * 7]
|
| 32 |
+
self.actions = [[0] * 4, [0] * 4]
|
| 33 |
+
self.power_games = [collections.Counter(), collections.Counter()]
|
| 34 |
+
self.guardians = [collections.Counter(), collections.Counter()]
|
| 35 |
+
self.by_god = {} # deus do agente -> [partidas, vitorias]
|
| 36 |
+
self.by_players = {} # numero de jogadores -> [partidas, vitorias, egito ateu]
|
| 37 |
+
self.seat_idx = {} # "P-assento" -> [partidas, vitorias]
|
| 38 |
+
self.roles = {} # papel na fusao -> [partidas, vitorias]
|
| 39 |
+
self.matrix = {} # "deus_agente-deus_oponente" -> [partidas, vitorias]
|
| 40 |
+
self.seat = {"first": [0, 0], "second": [0, 0]}
|
| 41 |
+
|
| 42 |
+
def add(self, s):
|
| 43 |
+
self.n += 1
|
| 44 |
+
c = self.c
|
| 45 |
+
c[s["result"]] += 1
|
| 46 |
+
for k in ("steps", "battles", "battle_ties", "tiebreak_used", "amun_double", "monuments_destroyed",
|
| 47 |
+
"pushes", "camels", "conflicts", "events"):
|
| 48 |
+
c[k] += s[k]
|
| 49 |
+
for i, who in enumerate(("me", "opp")):
|
| 50 |
+
c["dev_" + who] += s["dev_final"][i]
|
| 51 |
+
c["mon_" + who] += s["monuments"][i]
|
| 52 |
+
c["fol_" + who] += s["followers"][i]
|
| 53 |
+
c["bw_" + who] += s["battle_wins"][i]
|
| 54 |
+
c["dom_" + who] += s["dominations"][i]
|
| 55 |
+
c["kills_" + who] += s["kills"][i]
|
| 56 |
+
c["builds_" + who] += s["builds"][i]
|
| 57 |
+
c["unl_" + who] += len(s["unlocks"][i])
|
| 58 |
+
c["lost_" + who] += s["dev_lost"][i]
|
| 59 |
+
self.dev_src[i].update(s["dev_src"][i])
|
| 60 |
+
for k in range(7):
|
| 61 |
+
self.cards[i][k] += s["cards"][i][k]
|
| 62 |
+
for k in range(4):
|
| 63 |
+
self.actions[i][k] += s["actions"][i][k]
|
| 64 |
+
self.power_games[i].update(set(s["powers"][i]))
|
| 65 |
+
self.guardians[i].update(s["guardians"][i])
|
| 66 |
+
self.end[s["end_reason"]] += 1
|
| 67 |
+
win = s["result"] == "win"
|
| 68 |
+
g = self.by_god.setdefault(s["god"][0], [0, 0])
|
| 69 |
+
g[0] += 1
|
| 70 |
+
g[1] += win
|
| 71 |
+
if s["n_players"] == 2 and s["god"][1] is not None:
|
| 72 |
+
m = self.matrix.setdefault(f"{s['god'][0]}-{s['god'][1]}", [0, 0])
|
| 73 |
+
m[0] += 1
|
| 74 |
+
m[1] += win
|
| 75 |
+
bp = self.by_players.setdefault(str(s["n_players"]), [0, 0, 0])
|
| 76 |
+
bp[0] += 1
|
| 77 |
+
bp[1] += win
|
| 78 |
+
bp[2] += s["result"] == "draw"
|
| 79 |
+
if s["n_players"] > 2:
|
| 80 |
+
ro = self.roles.setdefault(s.get("merge_role") or "fora da fusao", [0, 0])
|
| 81 |
+
ro[0] += 1
|
| 82 |
+
ro[1] += win
|
| 83 |
+
sp = self.seat_idx.setdefault(f"{s['n_players']}-{s['me_seat']}", [0, 0])
|
| 84 |
+
sp[0] += 1
|
| 85 |
+
sp[1] += win
|
| 86 |
+
seat = self.seat["first" if s["me_first"] else "second"]
|
| 87 |
+
seat[0] += 1
|
| 88 |
+
seat[1] += win
|
| 89 |
+
|
| 90 |
+
def to_dict(self):
|
| 91 |
+
n = max(self.n, 1)
|
| 92 |
+
c = self.c
|
| 93 |
+
per = lambda k: c[k] / n
|
| 94 |
+
return {
|
| 95 |
+
"n": self.n, "win": c["win"] / n, "loss": c["loss"] / n, "draw": c["draw"] / n,
|
| 96 |
+
"steps": per("steps"), "events": per("events"), "conflicts": per("conflicts"), "camels": per("camels"),
|
| 97 |
+
"dev_me": per("dev_me"), "dev_opp": per("dev_opp"), "monuments_me": per("mon_me"),
|
| 98 |
+
"monuments_opp": per("mon_opp"), "followers_me": per("fol_me"), "followers_opp": per("fol_opp"),
|
| 99 |
+
"battles": per("battles"), "battle_wins_me": per("bw_me"), "battle_wins_opp": per("bw_opp"),
|
| 100 |
+
"battle_ties": per("battle_ties"), "dominations_me": per("dom_me"), "dominations_opp": per("dom_opp"),
|
| 101 |
+
"kills_me": per("kills_me"), "kills_opp": per("kills_opp"), "builds_me": per("builds_me"),
|
| 102 |
+
"builds_opp": per("builds_opp"), "unlocks_me": per("unl_me"), "unlocks_opp": per("unl_opp"),
|
| 103 |
+
"dev_lost_me": per("lost_me"), "tiebreak_used": per("tiebreak_used"), "amun_double": per("amun_double"),
|
| 104 |
+
"monuments_destroyed": per("monuments_destroyed"), "pushes": per("pushes"),
|
| 105 |
+
"end": {k: v / n for k, v in self.end.items()},
|
| 106 |
+
"dev_src_me": {k: v / n for k, v in self.dev_src[0].items()},
|
| 107 |
+
"dev_src_opp": {k: v / n for k, v in self.dev_src[1].items()},
|
| 108 |
+
"cards_me": [x / n for x in self.cards[0]], "cards_opp": [x / n for x in self.cards[1]],
|
| 109 |
+
"actions_me": [x / n for x in self.actions[0]], "actions_opp": [x / n for x in self.actions[1]],
|
| 110 |
+
"power_games_me": {POWER_NAMES[k]: v / n for k, v in self.power_games[0].items()},
|
| 111 |
+
"power_games_opp": {POWER_NAMES[k]: v / n for k, v in self.power_games[1].items()},
|
| 112 |
+
"guardians_me": {KIND_NAMES[k]: v / n for k, v in self.guardians[0].items()},
|
| 113 |
+
"guardians_opp": {KIND_NAMES[k]: v / n for k, v in self.guardians[1].items()},
|
| 114 |
+
"by_god": {str(k): v for k, v in self.by_god.items()},
|
| 115 |
+
"matrix": self.matrix, "seat": self.seat, "by_players": self.by_players, "seat_idx": self.seat_idx,
|
| 116 |
+
"merge_roles": self.roles,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def make_stats_callback(agg_round):
|
| 121 |
+
"""Callback do SB3: agrega as partidas de treino em `agg_round` e loga escalares no TensorBoard."""
|
| 122 |
+
from stable_baselines3.common.callbacks import BaseCallback
|
| 123 |
+
|
| 124 |
+
class StatsCallback(BaseCallback):
|
| 125 |
+
def __init__(self):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.roll = Agg()
|
| 128 |
+
|
| 129 |
+
def _on_step(self):
|
| 130 |
+
for info in self.locals.get("infos", []):
|
| 131 |
+
s = info.get("summary")
|
| 132 |
+
if s is not None:
|
| 133 |
+
agg_round.add(s)
|
| 134 |
+
self.roll.add(s)
|
| 135 |
+
return True
|
| 136 |
+
|
| 137 |
+
def _on_rollout_end(self):
|
| 138 |
+
if self.roll.n:
|
| 139 |
+
d = self.roll.to_dict()
|
| 140 |
+
for k in ("win", "draw", "steps", "dev_me", "dev_opp", "battles", "battle_wins_me",
|
| 141 |
+
"unlocks_me", "monuments_me"):
|
| 142 |
+
self.logger.record(f"ankh/{k}", d[k])
|
| 143 |
+
for k, v in d["end"].items():
|
| 144 |
+
self.logger.record(f"ankh/fim_{k}", v)
|
| 145 |
+
self.roll = Agg()
|
| 146 |
+
|
| 147 |
+
return StatsCallback()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def log_round(report_dir, record):
|
| 151 |
+
os.makedirs(report_dir, exist_ok=True)
|
| 152 |
+
with open(os.path.join(report_dir, "report.jsonl"), "a") as f:
|
| 153 |
+
f.write(json.dumps(record) + "\n")
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def read_rounds(report_dir):
|
| 157 |
+
path = os.path.join(report_dir, "report.jsonl")
|
| 158 |
+
if not os.path.exists(path):
|
| 159 |
+
return []
|
| 160 |
+
return [json.loads(l) for l in open(path) if l.strip()]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------
|
| 164 |
+
# Relatorio
|
| 165 |
+
# ---------------------------------------------------------------------------
|
| 166 |
+
pct = lambda x: f"{100 * x:.0f}%"
|
| 167 |
+
f1 = lambda x: f"{x:.1f}"
|
| 168 |
+
f2 = lambda x: f"{x:.2f}"
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _table(header, rows):
|
| 172 |
+
out = ["| " + " | ".join(header) + " |", "|" + "|".join("---" for _ in header) + "|"]
|
| 173 |
+
out += ["| " + " | ".join(str(c) for c in r) + " |" for r in rows]
|
| 174 |
+
return "\n".join(out)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _block(title, d):
|
| 178 |
+
"""Tabela-resumo de um agregado (treino ou avaliacao)."""
|
| 179 |
+
if not d or not d["n"]:
|
| 180 |
+
return ""
|
| 181 |
+
rows = [["partidas", d["n"]], ["vitorias / derrotas / Egito ateu", f"{pct(d['win'])} / {pct(d['loss'])} / {pct(d['draw'])}"],
|
| 182 |
+
["decisoes por partida", f1(d["steps"])], ["Devocao final (eu / oponente)", f"{f1(d['dev_me'])} / {f1(d['dev_opp'])}"],
|
| 183 |
+
["monumentos no fim (eu / oponente)", f"{f1(d['monuments_me'])} / {f1(d['monuments_opp'])}"],
|
| 184 |
+
["batalhas por partida (vitorias eu / oponente / empates)",
|
| 185 |
+
f"{f1(d['battles'])} ({f1(d['battle_wins_me'])} / {f1(d['battle_wins_opp'])} / {f1(d['battle_ties'])})"],
|
| 186 |
+
["dominios por partida (eu / oponente)", f"{f1(d['dominations_me'])} / {f1(d['dominations_opp'])}"],
|
| 187 |
+
["figuras minhas / do oponente mortas", f"{f1(d['kills_me'])} / {f1(d['kills_opp'])}"],
|
| 188 |
+
["poderes desbloqueados (eu / oponente)", f"{f1(d['unlocks_me'])} / {f1(d['unlocks_opp'])}"]]
|
| 189 |
+
return f"**{title}**\n\n" + _table(["metrica", "valor"], rows) + "\n"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _alerts(rounds):
|
| 193 |
+
out = []
|
| 194 |
+
last = rounds[-1]
|
| 195 |
+
er = last.get("eval_random")
|
| 196 |
+
if er and er["draw"] > 0.30:
|
| 197 |
+
out.append(f"{pct(er['draw'])} das partidas de avaliacao terminam em Egito ateu: o agente ainda nao sai do vermelho de forma consistente.")
|
| 198 |
+
prevs = [r["eval_prev"]["win"] for r in rounds[-3:] if r.get("eval_prev")]
|
| 199 |
+
if len(prevs) == 3 and min(prevs) >= 0.95:
|
| 200 |
+
out.append("O modelo vence ~100% contra o snapshot anterior por 3 rounds seguidos: o snapshot pode estar velho/fraco (aumente a frequencia de snapshots) ou o treino esta muito a frente.")
|
| 201 |
+
if er and er.get("by_god"):
|
| 202 |
+
rates = {int(k): v[1] / max(v[0], 1) for k, v in er["by_god"].items()}
|
| 203 |
+
if len(rates) > 1 and max(rates.values()) - min(rates.values()) > 0.30:
|
| 204 |
+
lo = min(rates, key=rates.get)
|
| 205 |
+
out.append(f"Diferenca grande entre deuses (contra aleatorio): {GODS[lo]} esta em {pct(rates[lo])} contra {pct(max(rates.values()))} do melhor.")
|
| 206 |
+
tr = last.get("train")
|
| 207 |
+
if tr and tr["n"] >= 20:
|
| 208 |
+
f_, s_ = tr["seat"]["first"], tr["seat"]["second"]
|
| 209 |
+
if f_[0] and s_[0] and abs(f_[1] / f_[0] - s_[1] / s_[0]) > 0.15:
|
| 210 |
+
out.append(f"Vantagem de posicao no treino: {pct(f_[1] / f_[0])} como 1o jogador contra {pct(s_[1] / s_[0])} como 2o.")
|
| 211 |
+
used = tr["cards_me"]
|
| 212 |
+
tot = sum(used) or 1
|
| 213 |
+
for k, u in enumerate(used):
|
| 214 |
+
if u / tot < 0.03:
|
| 215 |
+
out.append(f"A carta {CARD_NAMES_PT[k]} quase nunca e jogada ({pct(u / tot)} das jogadas).")
|
| 216 |
+
if tr["end"].get("egito_ateu", 0) > 0.40:
|
| 217 |
+
out.append(f"{pct(tr['end']['egito_ateu'])} das partidas de TREINO acabam em Egito ateu.")
|
| 218 |
+
return out
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def render_markdown(report_dir, plot=True):
|
| 222 |
+
rounds = read_rounds(report_dir)
|
| 223 |
+
if not rounds:
|
| 224 |
+
return None
|
| 225 |
+
last = rounds[-1]
|
| 226 |
+
L = [f"# Relatorio do treino ({os.path.basename(os.path.abspath(report_dir))})", "",
|
| 227 |
+
f"Round {last['round']} | {last['steps']:,} passos | {last.get('minutes', 0):.0f} min | "
|
| 228 |
+
f"recompensas: {last.get('rewards', '?')} | deuses: {last.get('gods', '?')}", ""]
|
| 229 |
+
alerts = _alerts(rounds)
|
| 230 |
+
if alerts:
|
| 231 |
+
L += ["## Alertas", ""] + [f"- {a}" for a in alerts] + [""]
|
| 232 |
+
L += ["## Evolucao (ultimos rounds)", ""]
|
| 233 |
+
rows = []
|
| 234 |
+
for r in rounds[-12:]:
|
| 235 |
+
e, p, t = r.get("eval_random"), r.get("eval_prev"), r.get("train")
|
| 236 |
+
rows.append([r["round"], f"{r['steps']:,}", pct(e["win"]) if e else "-", pct(e["draw"]) if e else "-",
|
| 237 |
+
pct(p["win"]) if p else "-", pct(t["win"]) if t and t["n"] else "-",
|
| 238 |
+
pct(t["draw"]) if t and t["n"] else "-", f1(t["steps"]) if t and t["n"] else "-",
|
| 239 |
+
f"{f1(t['dev_me'])}/{f1(t['dev_opp'])}" if t and t["n"] else "-", r.get("opponent", "")])
|
| 240 |
+
L += [_table(["round", "passos", "vit. vs aleat.", "ateu (aleat.)", "vit. vs anterior", "vit. treino",
|
| 241 |
+
"ateu treino", "decisoes/partida", "Devocao eu/opp (treino)", "treinou contra"], rows), ""]
|
| 242 |
+
L += ["## Ultimo round em detalhe", ""]
|
| 243 |
+
for title, key in (("Partidas de treino (contra o oponente do round)", "train"),
|
| 244 |
+
("Avaliacao contra jogador aleatorio", "eval_random"),
|
| 245 |
+
("Avaliacao contra o snapshot anterior", "eval_prev")):
|
| 246 |
+
b = _block(title, last.get(key))
|
| 247 |
+
if b:
|
| 248 |
+
L += [b]
|
| 249 |
+
tr = last.get("train")
|
| 250 |
+
if tr and tr["n"]:
|
| 251 |
+
L += ["## Como as partidas terminam (treino)", "",
|
| 252 |
+
_table(["motivo", "fracao"], [[END_NAMES.get(k, k), pct(v)] for k, v in sorted(tr["end"].items(), key=lambda x: -x[1])]), ""]
|
| 253 |
+
L += ["## Origem da Devocao por partida (treino)", "",
|
| 254 |
+
_table(["fonte", "eu", "oponente"],
|
| 255 |
+
[[k, f2(tr["dev_src_me"].get(k, 0)), f2(tr["dev_src_opp"].get(k, 0))]
|
| 256 |
+
for k in sorted(set(tr["dev_src_me"]) | set(tr["dev_src_opp"]))] +
|
| 257 |
+
[["Devocao perdida (Cat-Mummy)", f2(tr["dev_lost_me"]), "-"]]), ""]
|
| 258 |
+
L += ["## Acoes e cartas por partida (treino)", "",
|
| 259 |
+
_table(["", *ACTION_NAMES], [["eu", *[f1(x) for x in tr["actions_me"]]], ["oponente", *[f1(x) for x in tr["actions_opp"]]]]), "",
|
| 260 |
+
_table(["", *CARD_NAMES_PT], [["eu", *[f2(x) for x in tr["cards_me"]]], ["oponente", *[f2(x) for x in tr["cards_opp"]]]]), ""]
|
| 261 |
+
pw = sorted(tr["power_games_me"].items(), key=lambda x: -x[1])
|
| 262 |
+
L += ["## Poderes e Guardioes (fracao das partidas em que o agente os teve)", "",
|
| 263 |
+
_table(["poder", "eu", "oponente"], [[k, pct(v), pct(tr["power_games_opp"].get(k, 0))] for k, v in pw]), ""]
|
| 264 |
+
gd = [[KIND_NAMES[k], f2(tr["guardians_me"].get(KIND_NAMES[k], 0)), f2(tr["guardians_opp"].get(KIND_NAMES[k], 0))] for k in GUARDIAN_KINDS]
|
| 265 |
+
L += [_table(["guardiao", "eu (por partida)", "oponente"], gd), ""]
|
| 266 |
+
extra = [["Amun com 2 cartas", f2(tr["amun_double"])], ["desempates usados", f2(tr["tiebreak_used"])],
|
| 267 |
+
["monumentos destruidos por Scorpion", f2(tr["monuments_destroyed"])], ["empurroes de Satet", f2(tr["pushes"])],
|
| 268 |
+
["camelos no tabuleiro ao fim", f1(tr["camels"])]]
|
| 269 |
+
L += ["## Eventos raros (por partida, treino)", "", _table(["evento", "valor"], extra), ""]
|
| 270 |
+
s = tr["seat"]
|
| 271 |
+
L += ["## Primeiro x segundo jogador (treino)", "",
|
| 272 |
+
_table(["", "partidas", "vitorias"], [[k, v[0], pct(v[1] / v[0]) if v[0] else "-"] for k, v in s.items()]), ""]
|
| 273 |
+
for title, key in (("treino", "train"), ("avaliacao contra aleatorio", "eval_random")):
|
| 274 |
+
d = last.get(key)
|
| 275 |
+
if d and d.get("by_players"):
|
| 276 |
+
rows = [[p, v[0], pct(v[1] / max(v[0], 1)), pct(1 / int(p)), pct(v[2] / max(v[0], 1))]
|
| 277 |
+
for p, v in sorted(d["by_players"].items(), key=lambda x: int(x[0]))]
|
| 278 |
+
L += [f"## Por numero de jogadores ({title})", "",
|
| 279 |
+
_table(["jogadores", "partidas", "vitorias", "acaso (1/P)", "Egito ateu"], rows), ""]
|
| 280 |
+
seats = sorted(d["seat_idx"].items(), key=lambda x: (int(x[0].split("-")[0]), int(x[0].split("-")[1])))
|
| 281 |
+
L += [_table(["jogadores-assento", "partidas", "vitorias"],
|
| 282 |
+
[[k, v[0], pct(v[1] / max(v[0], 1))] for k, v in seats]), ""]
|
| 283 |
+
for title, key in (("treino", "train"), ("avaliacao contra aleatorio", "eval_random")):
|
| 284 |
+
d = last.get(key)
|
| 285 |
+
if d and d.get("merge_roles"):
|
| 286 |
+
tot = sum(v[0] for v in d["merge_roles"].values()) or 1
|
| 287 |
+
L += [f"## Fusao de deuses ({title}; partidas com 3+ jogadores)", "",
|
| 288 |
+
_table(["papel do agente", "partidas", "fracao", "vitorias"],
|
| 289 |
+
[[k, v[0], pct(v[0] / tot), pct(v[1] / max(v[0], 1))] for k, v in sorted(d["merge_roles"].items())]),
|
| 290 |
+
"", "Se o agente passar a ser 'absorvido' ou 'superior' com frequencia muito acima do esperado, ele pode estar buscando a fusao.", ""]
|
| 291 |
+
er = last.get("eval_random")
|
| 292 |
+
if er and er.get("by_god"):
|
| 293 |
+
rows = [[GODS[int(k)], v[0], pct(v[1] / max(v[0], 1))] for k, v in sorted(er["by_god"].items(), key=lambda x: int(x[0]))]
|
| 294 |
+
L += ["## Por deus (avaliacao contra aleatorio)", "", _table(["deus", "partidas", "vitorias"], rows), ""]
|
| 295 |
+
mats = [r for r in rounds if r.get("matrix")]
|
| 296 |
+
if mats:
|
| 297 |
+
m = mats[-1]["matrix"]
|
| 298 |
+
pool = sorted({int(k.split("-")[0]) for k in m} | {int(k.split("-")[1]) for k in m})
|
| 299 |
+
rows = []
|
| 300 |
+
for a in pool:
|
| 301 |
+
rows.append([GODS[a]] + [("-" if a == b or f"{a}-{b}" not in m else
|
| 302 |
+
f"{pct(m[f'{a}-{b}'][1] / max(m[f'{a}-{b}'][0], 1))} ({m[f'{a}-{b}'][0]})") for b in pool])
|
| 303 |
+
L += [f"## Confrontos entre deuses (round {mats[-1]['round']}; linha = deus do modelo, coluna = deus do oponente; vitorias do modelo contra {mats[-1].get('matrix_vs', '?')})", "",
|
| 304 |
+
_table(["", *[GODS[b] for b in pool]], rows), ""]
|
| 305 |
+
text = "\n".join(L)
|
| 306 |
+
with open(os.path.join(report_dir, "relatorio.md"), "w") as f:
|
| 307 |
+
f.write(text)
|
| 308 |
+
if plot:
|
| 309 |
+
try:
|
| 310 |
+
_plot(rounds, report_dir)
|
| 311 |
+
except Exception:
|
| 312 |
+
pass
|
| 313 |
+
return text
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _plot(rounds, report_dir):
|
| 317 |
+
import matplotlib
|
| 318 |
+
matplotlib.use("Agg")
|
| 319 |
+
import matplotlib.pyplot as plt
|
| 320 |
+
x = [r["steps"] for r in rounds]
|
| 321 |
+
get = lambda key, f: [f(r[key]) if r.get(key) and r[key]["n"] else float("nan") for r in rounds]
|
| 322 |
+
fig, ax = plt.subplots(2, 2, figsize=(12, 7))
|
| 323 |
+
ax[0, 0].plot(x, get("eval_random", lambda d: d["win"]), "o-", label="vs aleatorio")
|
| 324 |
+
ax[0, 0].plot(x, get("eval_prev", lambda d: d["win"]), "o-", label="vs snapshot anterior")
|
| 325 |
+
ax[0, 0].plot(x, get("train", lambda d: d["win"]), "o-", label="treino")
|
| 326 |
+
ax[0, 0].set_title("vitorias"); ax[0, 0].set_ylim(0, 1); ax[0, 0].legend()
|
| 327 |
+
ax[0, 1].plot(x, get("eval_random", lambda d: d["draw"]), "o-", label="aleatorio")
|
| 328 |
+
ax[0, 1].plot(x, get("train", lambda d: d["draw"]), "o-", label="treino")
|
| 329 |
+
ax[0, 1].set_title("Egito ateu"); ax[0, 1].set_ylim(0, 1); ax[0, 1].legend()
|
| 330 |
+
ax[1, 0].plot(x, get("train", lambda d: d["steps"]), "o-"); ax[1, 0].set_title("decisoes por partida (treino)")
|
| 331 |
+
ax[1, 1].plot(x, get("train", lambda d: d["dev_me"]), "o-", label="eu")
|
| 332 |
+
ax[1, 1].plot(x, get("train", lambda d: d["dev_opp"]), "o-", label="oponente")
|
| 333 |
+
ax[1, 1].set_title("Devocao final (treino)"); ax[1, 1].legend()
|
| 334 |
+
for a in ax.flat:
|
| 335 |
+
a.set_xlabel("passos")
|
| 336 |
+
fig.tight_layout()
|
| 337 |
+
fig.savefig(os.path.join(report_dir, "curvas.png"), dpi=110)
|
| 338 |
+
plt.close(fig)
|
ankh_vec.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_vec.py - VecEnv (stable-baselines3) com simulacao em processos de CPU e
|
| 3 |
+
inferencia do oponente EM LOTE na GPU.
|
| 4 |
+
|
| 5 |
+
O que roda onde
|
| 6 |
+
---------------
|
| 7 |
+
* Regras do jogo + codificacao da observacao: CPU, em `n_workers` processos
|
| 8 |
+
(cada um com varias partidas). Python puro: nao da para rodar na GPU sem
|
| 9 |
+
reescrever o jogo como operacoes de tensor.
|
| 10 |
+
* Politica do agente (SB3) e do oponente (snapshot): GPU, uma chamada por lote
|
| 11 |
+
com TODAS as partidas que esperam decisao. O PPO tambem atualiza na GPU.
|
| 12 |
+
|
| 13 |
+
Uso:
|
| 14 |
+
venv = BatchedSelfPlayVecEnv(n_envs=64, n_workers=2) # crie ANTES do modelo
|
| 15 |
+
venv.set_opponent(None) # aleatorio (roda dentro dos workers)
|
| 16 |
+
venv.set_opponent(TorchOpponent(path)) # rede em lote na GPU
|
| 17 |
+
"""
|
| 18 |
+
import multiprocessing as mp
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from gymnasium import spaces
|
| 22 |
+
from stable_baselines3.common.vec_env import VecEnv
|
| 23 |
+
|
| 24 |
+
from ankh_game import AnkhGame
|
| 25 |
+
from ankh_obs import Encoder
|
| 26 |
+
from ankh_worker import worker_main
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BatchedSelfPlayVecEnv(VecEnv):
|
| 30 |
+
def __init__(self, n_envs=64, n_workers=2, scenarios=None, seed=0,
|
| 31 |
+
dev_gain=0.02, dev_opp=0.01, war_gain=0.005, war_opp=0.0025,
|
| 32 |
+
draw_reward=-1.0, zero_sum=False, god_pool=None, merged_reward="normal",
|
| 33 |
+
start_method="spawn"):
|
| 34 |
+
# zero_sum=True: o que um jogador ganha o outro perde (pesos simetricos e
|
| 35 |
+
# Egito ateu = 0), para o self-play competitivo depois do pre-treino.
|
| 36 |
+
if zero_sum:
|
| 37 |
+
dev_opp, war_opp, draw_reward = dev_gain, war_gain, 0.0
|
| 38 |
+
from ankh_map import SCENARIOS
|
| 39 |
+
scenarios = list(scenarios) if scenarios else list(SCENARIOS) # padrao: todos os cenarios validos
|
| 40 |
+
probe = AnkhGame(scenarios)
|
| 41 |
+
self.scenarios = list(probe.scenarios)
|
| 42 |
+
self.skipped = dict(probe.skipped) # cenarios com erro de dados
|
| 43 |
+
probe.reset(seed=0)
|
| 44 |
+
obs_dim, a_size = len(Encoder(probe).encode(probe.decision)), probe.A_SIZE
|
| 45 |
+
super().__init__(n_envs, spaces.Box(0.0, 1.0, (obs_dim,), np.float32), spaces.Discrete(a_size))
|
| 46 |
+
self.obs_dim, self.a_size = obs_dim, a_size
|
| 47 |
+
cfg = dict(dev_gain=dev_gain, dev_opp=dev_opp, war_gain=war_gain, war_opp=war_opp, draw=draw_reward, merged_reward=merged_reward,
|
| 48 |
+
god_pool=list(god_pool) if god_pool else None)
|
| 49 |
+
ctx = mp.get_context(start_method) # 'spawn': nao herda estado da GPU
|
| 50 |
+
self.chunks = [list(c) for c in np.array_split(np.arange(n_envs), min(n_workers, n_envs)) if len(c)]
|
| 51 |
+
self.local = {}
|
| 52 |
+
self.pipes, self.procs = [], []
|
| 53 |
+
for w, ids in enumerate(self.chunks):
|
| 54 |
+
parent, child = ctx.Pipe()
|
| 55 |
+
p = ctx.Process(target=worker_main, args=(child, len(ids), seed + 1000 * w, self.scenarios, cfg), daemon=True)
|
| 56 |
+
p.start()
|
| 57 |
+
child.close()
|
| 58 |
+
self.pipes.append(parent)
|
| 59 |
+
self.procs.append(p)
|
| 60 |
+
for i, s in enumerate(ids):
|
| 61 |
+
self.local[s] = (w, i)
|
| 62 |
+
self._obs = np.zeros((n_envs, obs_dim), np.float32)
|
| 63 |
+
self._mask = np.zeros((n_envs, a_size), bool)
|
| 64 |
+
self._ret = np.zeros(n_envs)
|
| 65 |
+
self._len = np.zeros(n_envs, int)
|
| 66 |
+
self._opponent = None
|
| 67 |
+
self._actions = None
|
| 68 |
+
self.set_opponent(None)
|
| 69 |
+
|
| 70 |
+
# ---------------- comunicacao ----------------
|
| 71 |
+
def _apply(self, items):
|
| 72 |
+
sent = []
|
| 73 |
+
for w, ids in enumerate(self.chunks):
|
| 74 |
+
mine = [s for s in ids if s in items]
|
| 75 |
+
if mine:
|
| 76 |
+
self.pipes[w].send(("apply", ([self.local[s][1] for s in mine], [items[s] for s in mine])))
|
| 77 |
+
sent.append((w, mine))
|
| 78 |
+
out = {}
|
| 79 |
+
for w, mine in sent:
|
| 80 |
+
for s, r in zip(mine, self.pipes[w].recv()):
|
| 81 |
+
out[s] = r
|
| 82 |
+
return out
|
| 83 |
+
|
| 84 |
+
def set_opponent(self, opponent):
|
| 85 |
+
"""None = aleatorio nos workers; senao callable(obs[B,D], mask[B,A]) -> acoes[B]."""
|
| 86 |
+
self._opponent = opponent
|
| 87 |
+
for p in self.pipes:
|
| 88 |
+
p.send(("opp_random", opponent is None))
|
| 89 |
+
for p in self.pipes:
|
| 90 |
+
p.recv()
|
| 91 |
+
|
| 92 |
+
def _opp_actions(self, obs, mask):
|
| 93 |
+
acts = np.asarray(self._opponent(obs, mask)).astype(int)
|
| 94 |
+
ok = mask[np.arange(len(acts)), acts]
|
| 95 |
+
for k in np.flatnonzero(~ok): # rede devolveu acao ilegal: sorteia legal
|
| 96 |
+
acts[k] = np.random.choice(np.flatnonzero(mask[k]))
|
| 97 |
+
return acts
|
| 98 |
+
|
| 99 |
+
def _run_until_agent(self, results, rew=None, done=None, infos=None):
|
| 100 |
+
"""Aplica em lote as jogadas do oponente ate todas as partidas esperarem o agente."""
|
| 101 |
+
while True:
|
| 102 |
+
opp = []
|
| 103 |
+
for s, (kind, obs, mask, ep, acc) in results.items():
|
| 104 |
+
if ep is not None and rew is not None:
|
| 105 |
+
rew[s], done[s], infos[s] = ep[0], True, dict(ep[1])
|
| 106 |
+
if kind == "agent":
|
| 107 |
+
self._obs[s], self._mask[s] = obs, mask
|
| 108 |
+
if rew is not None and not done[s]:
|
| 109 |
+
rew[s] = acc
|
| 110 |
+
else:
|
| 111 |
+
opp.append(s)
|
| 112 |
+
if not opp:
|
| 113 |
+
return
|
| 114 |
+
obs_b = np.stack([results[s][1] for s in opp])
|
| 115 |
+
mask_b = np.stack([results[s][2] for s in opp])
|
| 116 |
+
acts = self._opp_actions(obs_b, mask_b)
|
| 117 |
+
results = self._apply({s: int(a) for s, a in zip(opp, acts)})
|
| 118 |
+
|
| 119 |
+
# ---------------- API do VecEnv ----------------
|
| 120 |
+
def reset(self):
|
| 121 |
+
for p in self.pipes:
|
| 122 |
+
p.send(("reset", None))
|
| 123 |
+
results = {}
|
| 124 |
+
for w, ids in enumerate(self.chunks):
|
| 125 |
+
for s, r in zip(ids, self.pipes[w].recv()):
|
| 126 |
+
results[s] = r
|
| 127 |
+
self._run_until_agent(results)
|
| 128 |
+
self._ret[:], self._len[:] = 0, 0
|
| 129 |
+
return self._obs.copy()
|
| 130 |
+
|
| 131 |
+
def step_async(self, actions):
|
| 132 |
+
self._actions = np.asarray(actions)
|
| 133 |
+
|
| 134 |
+
def step_wait(self):
|
| 135 |
+
n = self.num_envs
|
| 136 |
+
rew, done, infos = np.zeros(n, np.float32), np.zeros(n, bool), [{} for _ in range(n)]
|
| 137 |
+
results = self._apply({s: int(a) for s, a in enumerate(self._actions)})
|
| 138 |
+
self._run_until_agent(results, rew, done, infos)
|
| 139 |
+
self._ret += rew
|
| 140 |
+
self._len += 1
|
| 141 |
+
for s in np.flatnonzero(done):
|
| 142 |
+
infos[s]["terminal_observation"] = np.zeros(self.obs_dim, np.float32)
|
| 143 |
+
infos[s]["episode"] = {"r": float(self._ret[s]), "l": int(self._len[s])}
|
| 144 |
+
self._ret[s], self._len[s] = 0, 0
|
| 145 |
+
return self._obs.copy(), rew, done, infos
|
| 146 |
+
|
| 147 |
+
def close(self):
|
| 148 |
+
for p in self.pipes:
|
| 149 |
+
try:
|
| 150 |
+
p.send(("close", None))
|
| 151 |
+
except (BrokenPipeError, OSError):
|
| 152 |
+
pass
|
| 153 |
+
for pr in self.procs:
|
| 154 |
+
pr.join(timeout=5)
|
| 155 |
+
|
| 156 |
+
def _idx(self, indices):
|
| 157 |
+
return range(self.num_envs) if indices is None else ([indices] if isinstance(indices, int) else list(indices))
|
| 158 |
+
|
| 159 |
+
def env_method(self, method_name, *args, indices=None, **kwargs):
|
| 160 |
+
idx = self._idx(indices)
|
| 161 |
+
if method_name == "action_masks":
|
| 162 |
+
return [self._mask[i].copy() for i in idx]
|
| 163 |
+
if method_name == "set_opponent":
|
| 164 |
+
self.set_opponent(args[0])
|
| 165 |
+
return [None] * len(idx)
|
| 166 |
+
raise ValueError(f"metodo nao suportado: {method_name}")
|
| 167 |
+
|
| 168 |
+
def get_attr(self, attr_name, indices=None):
|
| 169 |
+
return [None] * len(self._idx(indices))
|
| 170 |
+
|
| 171 |
+
def set_attr(self, attr_name, value, indices=None):
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
def env_is_wrapped(self, wrapper_class, indices=None):
|
| 175 |
+
return [False] * len(self._idx(indices))
|
| 176 |
+
|
| 177 |
+
def get_images(self):
|
| 178 |
+
return [None] * self.num_envs
|
| 179 |
+
|
| 180 |
+
def seed(self, seed=None):
|
| 181 |
+
return [None] * self.num_envs
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class TorchOpponent:
|
| 185 |
+
"""Snapshot do MaskablePPO carregado na GPU; decide em lote."""
|
| 186 |
+
def __init__(self, path, device="cuda"):
|
| 187 |
+
import torch
|
| 188 |
+
from sb3_contrib import MaskablePPO
|
| 189 |
+
self.torch = torch
|
| 190 |
+
self.model = MaskablePPO.load(path, device=device)
|
| 191 |
+
self.policy = self.model.policy
|
| 192 |
+
self.policy.set_training_mode(False)
|
| 193 |
+
|
| 194 |
+
def __call__(self, obs, mask):
|
| 195 |
+
torch = self.torch
|
| 196 |
+
with torch.no_grad():
|
| 197 |
+
o = torch.as_tensor(obs, dtype=torch.float32, device=self.policy.device)
|
| 198 |
+
a, _, _ = self.policy.forward(o, deterministic=False, action_masks=mask)
|
| 199 |
+
return a.cpu().numpy()
|
ankh_worker.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ankh_worker.py - Processo que roda varias partidas de Ankh (CPU) para o VecEnv.
|
| 3 |
+
|
| 4 |
+
Nao depende de gymnasium nem de stable-baselines3 (para o processo 'spawn'
|
| 5 |
+
iniciar rapido e sem tocar na GPU). Cada "slot" e uma partida com um ASSENTO do
|
| 6 |
+
agente (`me`, sorteado por episodio entre os P assentos do cenario sorteado) e
|
| 7 |
+
os demais assentos controlados por um oponente (a rede na GPU, em lote, ou
|
| 8 |
+
jogadas aleatorias dentro do proprio worker). O worker devolve a proxima
|
| 9 |
+
decisao pendente:
|
| 10 |
+
kind='agent' -> o agente deve agir; kind='opp' -> um oponente deve agir.
|
| 11 |
+
|
| 12 |
+
Recompensa do agente: fim de jogo (+1 vitoria, -1/(P-1) derrota, `draw` no Egito
|
| 13 |
+
ateu; com P=2 a derrota vale -1); + dev_gain por casa de Devocao que o agente subiu,
|
| 14 |
+
- dev_opp pela media das casas que os oponentes subiram; idem guerreiros no
|
| 15 |
+
tabuleiro (war_gain / war_opp). Se ele esta num deus fundido, a recompensa e da
|
| 16 |
+
entidade fundida.
|
| 17 |
+
"""
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from ankh_game import AnkhGame
|
| 21 |
+
from ankh_map import build_board
|
| 22 |
+
from ankh_obs import Encoder
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _unpack(t):
|
| 26 |
+
"""Aceita o formato antigo (dev_eu, dev_op, guerr_eu, guerr_op) e o novo (com dicts por oponente)."""
|
| 27 |
+
if len(t) == 4:
|
| 28 |
+
return t[0], {0: t[1]}, t[2], {0: t[3]}, None
|
| 29 |
+
return t
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def reward_parts(c, prev, now):
|
| 33 |
+
"""(r_dev, r_war) de uma transicao, do ponto de vista do agente."""
|
| 34 |
+
pd, pod, pw, pow_, pe = _unpack(prev)
|
| 35 |
+
nd, nod, nw, now_, ne = _unpack(now)
|
| 36 |
+
if pe != ne: # a entidade do agente mudou (fusao): sem delta nesse passo
|
| 37 |
+
return 0.0, 0.0
|
| 38 |
+
common = [e for e in nod if e in pod]
|
| 39 |
+
mean = lambda xs: sum(xs) / len(xs) if xs else 0.0
|
| 40 |
+
d_opp = mean([nod[e] - pod[e] for e in common])
|
| 41 |
+
w_opp = mean([now_[e] - pow_[e] for e in common])
|
| 42 |
+
return (c["dev_gain"] * (nd - pd) - c["dev_opp"] * d_opp,
|
| 43 |
+
c["war_gain"] * (nw - pw) - c["war_opp"] * w_opp)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def step_reward(c, prev, now):
|
| 47 |
+
"""Recompensa densa total de uma transicao."""
|
| 48 |
+
a, b = reward_parts(c, prev, now)
|
| 49 |
+
return a + b
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def end_reward(c, me, winner, n_players=2):
|
| 53 |
+
"""+1 vitoria, -1/(P-1) derrota (P=2: -1), c['draw'] se todos os deuses foram esquecidos."""
|
| 54 |
+
if winner is None:
|
| 55 |
+
return c["draw"]
|
| 56 |
+
return 1.0 if winner == me else -1.0 / (n_players - 1)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def snapshot(g, me):
|
| 60 |
+
"""Estado relevante para a recompensa do assento `me`. Usa a Devocao acumulada `rdev` (que a
|
| 61 |
+
fusao NAO altera) e os guerreiros no tabuleiro: assim a fusao em si nao gera nem tira recompensa."""
|
| 62 |
+
r = g.rep[me]
|
| 63 |
+
opps = [e for e in range(g.P) if e != r and g.rep[e] == e and g.alive[e]]
|
| 64 |
+
return (g.rdev[r], {e: g.rdev[e] for e in opps}, g.board_warriors(r),
|
| 65 |
+
{e: g.board_warriors(e) for e in opps}, r)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def merged_seat(g, me):
|
| 69 |
+
"""O assento `me` pertence a um deus fundido (superior ou absorvido)?"""
|
| 70 |
+
return g.merged is not None and me in g.merged
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class Slot:
|
| 74 |
+
def __init__(self, board, scenarios, seed, cfg):
|
| 75 |
+
self.g = AnkhGame(scenarios, seed=seed, board=board, god_pool=cfg.get("god_pool"))
|
| 76 |
+
self.enc = Encoder(self.g)
|
| 77 |
+
self.rng = np.random.default_rng(seed)
|
| 78 |
+
self.cfg = cfg
|
| 79 |
+
self.start()
|
| 80 |
+
|
| 81 |
+
def start(self):
|
| 82 |
+
self.g.reset(seed=int(self.rng.integers(2**31))) # sorteia cenario e deuses
|
| 83 |
+
self.me = int(self.rng.integers(self.g.P)) # assento do agente
|
| 84 |
+
self.fresh, self.acc, self.prev = True, 0.0, None # aberturas dos oponentes nao dao recompensa
|
| 85 |
+
|
| 86 |
+
def snap(self):
|
| 87 |
+
return snapshot(self.g, self.me)
|
| 88 |
+
|
| 89 |
+
def apply(self, a):
|
| 90 |
+
g, c = self.g, self.cfg
|
| 91 |
+
g.step(int(a))
|
| 92 |
+
zero = c.get("merged_reward") == "zero" and merged_seat(g, self.me) # modo estrito
|
| 93 |
+
if not self.fresh:
|
| 94 |
+
now = self.snap()
|
| 95 |
+
if not zero:
|
| 96 |
+
self.acc += step_reward(c, self.prev, now)
|
| 97 |
+
self.prev = now
|
| 98 |
+
if g.done:
|
| 99 |
+
r = g.rep[self.me]
|
| 100 |
+
end = 0.0 if zero else end_reward(c, r, g.winner, g.P)
|
| 101 |
+
opp0 = next((e for e in range(g.P) if e != r and g.rep[e] == e), None)
|
| 102 |
+
ep = (self.acc + end, {"winner": g.winner, "me": self.me, "r_end": end,
|
| 103 |
+
"god_me": g.god[r], "god_opp": g.god[opp0] if opp0 is not None else None,
|
| 104 |
+
"summary": g.summary(self.me)})
|
| 105 |
+
self.start()
|
| 106 |
+
return ep
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
def result(self, ep, random_opp):
|
| 110 |
+
g = self.g
|
| 111 |
+
while True:
|
| 112 |
+
if g.decision.player == self.me:
|
| 113 |
+
if self.fresh:
|
| 114 |
+
self.prev, self.fresh, self.acc = self.snap(), False, 0.0
|
| 115 |
+
kind = "agent"
|
| 116 |
+
break
|
| 117 |
+
if not random_opp:
|
| 118 |
+
kind = "opp"
|
| 119 |
+
break
|
| 120 |
+
e = self.apply(self.rng.choice(np.flatnonzero(g.decision.mask)))
|
| 121 |
+
ep = e if e is not None else ep
|
| 122 |
+
dec = g.decision
|
| 123 |
+
acc = 0.0
|
| 124 |
+
if kind == "agent":
|
| 125 |
+
acc, self.acc = self.acc, 0.0
|
| 126 |
+
return (kind, self.enc.encode(dec), dec.mask, ep, acc)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def worker_main(conn, n_slots, seed, scenarios, cfg):
|
| 130 |
+
board = build_board()
|
| 131 |
+
slots = [Slot(board, scenarios, seed + i, cfg) for i in range(n_slots)]
|
| 132 |
+
random_opp = True
|
| 133 |
+
try:
|
| 134 |
+
while True:
|
| 135 |
+
cmd, data = conn.recv()
|
| 136 |
+
if cmd == "reset":
|
| 137 |
+
for s in slots:
|
| 138 |
+
s.start()
|
| 139 |
+
conn.send([s.result(None, random_opp) for s in slots])
|
| 140 |
+
elif cmd == "apply":
|
| 141 |
+
ids, actions = data
|
| 142 |
+
conn.send([slots[i].result(slots[i].apply(a), random_opp) for i, a in zip(ids, actions)])
|
| 143 |
+
elif cmd == "opp_random":
|
| 144 |
+
random_opp = bool(data)
|
| 145 |
+
conn.send(True)
|
| 146 |
+
elif cmd == "close":
|
| 147 |
+
break
|
| 148 |
+
finally:
|
| 149 |
+
conn.close()
|
jogar.html
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="pt-BR">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Ankh — Gods of Egypt</title>
|
| 7 |
+
<style>
|
| 8 |
+
:root{
|
| 9 |
+
--wood:#2b1d12;--parch1:#f0e2bb;--parch2:#dcc58f;--ink:#3a2a14;--gold:#d9a93a;--gold2:#b8923a;
|
| 10 |
+
--red:#8a2a1c;--dark:#2a1b10;--dark2:#3a2616;--cream:#f6ead0;--ok:#00e676;--blue:#2f7fd1;
|
| 11 |
+
--serif:'Cinzel','Trajan Pro','Palatino Linotype','Book Antiqua',Georgia,serif;
|
| 12 |
+
}
|
| 13 |
+
*{box-sizing:border-box}
|
| 14 |
+
html{background:#2b1d12}
|
| 15 |
+
body{margin:0;color:var(--ink);font:14px/1.35 'Segoe UI',system-ui,Roboto,sans-serif;min-height:100vh;
|
| 16 |
+
background:repeating-linear-gradient(90deg,rgba(0,0,0,.10) 0 2px,transparent 2px 9px),
|
| 17 |
+
radial-gradient(ellipse at 50% 0%,rgba(255,200,120,.12),transparent 60%),#2b1d12;
|
| 18 |
+
background-attachment:fixed}
|
| 19 |
+
button,select,input{font:inherit}
|
| 20 |
+
header{display:flex;gap:10px;align-items:center;padding:8px 16px;background:linear-gradient(#1b120a,#2a1b10);
|
| 21 |
+
border-bottom:3px solid var(--gold2);box-shadow:0 3px 10px rgba(0,0,0,.6)}
|
| 22 |
+
header h1{margin:0;font:700 22px var(--serif);color:var(--gold);letter-spacing:3px;text-shadow:0 2px 0 #000}
|
| 23 |
+
header .meta{color:#bfa56a;font-size:12px}
|
| 24 |
+
header .sp{flex:1}
|
| 25 |
+
.btn{background:linear-gradient(#c9a24a,#9a7424);color:#2a1b08;border:2px solid #5a3b10;border-radius:7px;
|
| 26 |
+
padding:5px 12px;font-weight:700;cursor:pointer;box-shadow:0 2px 0 #4a3008}
|
| 27 |
+
.btn:hover{filter:brightness(1.12)}
|
| 28 |
+
.btn:active{transform:translateY(1px)}
|
| 29 |
+
.btn.sm{padding:3px 8px;font-size:12px}
|
| 30 |
+
.btn:disabled{opacity:.45;cursor:default}
|
| 31 |
+
.btn.dark{background:linear-gradient(#4a3a28,#2f2418);color:var(--cream);border-color:#7a5a28}
|
| 32 |
+
select.sel{background:#2f2418;color:var(--cream);border:2px solid #7a5a28;border-radius:6px;padding:3px 6px}
|
| 33 |
+
.hdrlab{color:#bfa56a;font-size:12px}
|
| 34 |
+
|
| 35 |
+
#table{display:grid;grid-template-columns:350px minmax(0,1fr) 300px;gap:12px;padding:12px 14px;align-items:start}
|
| 36 |
+
#table .dark:last-child,#table .parch:last-child{margin-bottom:0}
|
| 37 |
+
@media(max-width:1250px){#table{grid-template-columns:330px minmax(0,1fr)}#rightcol{grid-column:1/-1;display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}#rightcol .dark{margin-bottom:0}}
|
| 38 |
+
@media(max-width:860px){#table{grid-template-columns:1fr}#centercol{order:-1}}
|
| 39 |
+
.parch{background:linear-gradient(145deg,var(--parch1),var(--parch2));border:3px solid var(--gold2);border-radius:12px;
|
| 40 |
+
box-shadow:inset 0 0 22px rgba(120,80,20,.35),0 4px 10px rgba(0,0,0,.55);padding:10px 12px;margin-bottom:12px}
|
| 41 |
+
.parch h2,.dark h2{margin:0 0 6px;font:700 13px var(--serif);letter-spacing:2px;text-transform:uppercase;color:#7b3f12}
|
| 42 |
+
.dark{background:linear-gradient(160deg,var(--dark2),var(--dark));color:var(--cream);border:3px solid var(--gold2);
|
| 43 |
+
border-radius:12px;box-shadow:inset 0 0 24px rgba(0,0,0,.6),0 4px 10px rgba(0,0,0,.55);padding:10px 12px;margin-bottom:12px}
|
| 44 |
+
.dark h2{color:var(--gold)}
|
| 45 |
+
.hint{font-size:12px;opacity:.8}
|
| 46 |
+
|
| 47 |
+
/* mesa de oponentes */
|
| 48 |
+
#opps{display:flex;gap:10px;flex-wrap:wrap;padding:10px 14px 0}
|
| 49 |
+
#opps:empty{display:none}
|
| 50 |
+
.opp{flex:1 1 210px;max-width:440px;border:3px solid var(--gold2);border-radius:11px;overflow:hidden;
|
| 51 |
+
background:linear-gradient(160deg,var(--dark2),var(--dark));color:var(--cream);box-shadow:0 4px 9px rgba(0,0,0,.55)}
|
| 52 |
+
.opp.turn{box-shadow:0 0 0 3px #ffd54a,0 0 18px #ffd54a}
|
| 53 |
+
.opp.dead{opacity:.45}
|
| 54 |
+
.opp .hd{padding:4px 9px;font:700 14px var(--serif);display:flex;gap:8px;align-items:center;color:#fff;text-shadow:0 1px 2px #000}
|
| 55 |
+
.opp .bd{padding:5px 9px;font-size:12px}
|
| 56 |
+
.chip{display:inline-block;font-size:10.5px;padding:0 5px;border-radius:7px;margin:1px 2px 0 0;background:#4a3a28;color:var(--cream)}
|
| 57 |
+
.chip.l1{background:#3b6a3b}.chip.l2{background:#3b5a8a}.chip.l3{background:#7a3b6a}
|
| 58 |
+
.chip.bad{background:#8a2a1c}.chip.warn{background:#8a6a1c}
|
| 59 |
+
.mini{display:inline-block;width:14px;height:18px;border-radius:3px;margin-right:2px;background:#6b5a3a;vertical-align:middle;border:1px solid #1b120a}
|
| 60 |
+
.mini.used{background:#a8442a}
|
| 61 |
+
.stat{display:inline-block;margin-right:9px}
|
| 62 |
+
|
| 63 |
+
/* painel central (acoes + eventos) */
|
| 64 |
+
.arow{display:flex;align-items:center;gap:4px;padding:4px 5px;margin:3px 0;border-radius:8px;background:rgba(0,0,0,.25);border:2px solid transparent}
|
| 65 |
+
.arow b{width:98px;font:700 11.5px var(--serif);color:var(--gold);line-height:1.1}
|
| 66 |
+
.arow .slot{width:23px;height:23px;border-radius:50%;background:radial-gradient(circle at 35% 30%,#5a4630,#2a1d10);border:2px solid #7a5a28;display:inline-block;position:relative}
|
| 67 |
+
.arow .slot.off{background:#120c07;border-color:#2a1d10}
|
| 68 |
+
.arow .slot.end{background:radial-gradient(circle at 35% 30%,#fff,#d9c9a0);border-color:#c0392b}
|
| 69 |
+
.arow .slot.end::after{content:'!';position:absolute;inset:0;text-align:center;font:700 14px/19px serif;color:#8a2a1c}
|
| 70 |
+
.arow .slot.mk{background:radial-gradient(circle at 35% 30%,#ffe28a,#c9951c);border-color:#fff3c0;box-shadow:0 0 8px #ffd54a}
|
| 71 |
+
.arow.legal{border-color:var(--ok);cursor:pointer;box-shadow:0 0 10px rgba(0,230,118,.5)}
|
| 72 |
+
.arow.legal:hover{background:rgba(0,230,118,.18)}
|
| 73 |
+
.arow.picked{border-color:#ffd54a;background:rgba(255,213,74,.25)}
|
| 74 |
+
.arow.flash{animation:flash 1s ease-out 2}
|
| 75 |
+
@keyframes flash{0%,100%{background:rgba(0,0,0,.25)}40%{background:rgba(255,213,74,.5)}}
|
| 76 |
+
.evgrid{display:grid;grid-template-columns:repeat(6,1fr);gap:5px;margin-top:4px}
|
| 77 |
+
.ev{aspect-ratio:1;border-radius:50%;background:radial-gradient(circle at 35% 30%,#4a3a28,#1d130b);border:2px solid #7a5a28;
|
| 78 |
+
display:flex;align-items:center;justify-content:center;font-size:15px;position:relative;color:var(--cream)}
|
| 79 |
+
.ev.conf{border-radius:7px;background:radial-gradient(circle at 35% 30%,#7a2f20,#3a130b);border-color:#c0663a}
|
| 80 |
+
.ev.camel{border-color:#c9a24a}
|
| 81 |
+
.ev.done{opacity:.38}
|
| 82 |
+
.ev.next{box-shadow:0 0 0 2px #ffd54a}
|
| 83 |
+
.ev.cur::before{content:'';position:absolute;inset:-5px;border-radius:50%;border:3px solid var(--blue);box-shadow:0 0 9px var(--blue)}
|
| 84 |
+
.ev small{position:absolute;bottom:-1px;right:2px;font:700 8.5px sans-serif;color:#ffd54a}
|
| 85 |
+
.evnote{font-size:11px;color:#bfa56a;margin-top:6px}
|
| 86 |
+
|
| 87 |
+
/* tabuleiro */
|
| 88 |
+
#boardframe{position:relative;border:8px solid #6b4a1c;border-radius:14px;
|
| 89 |
+
box-shadow:0 0 0 3px var(--gold),0 8px 18px rgba(0,0,0,.7),inset 0 0 30px rgba(0,0,0,.5);
|
| 90 |
+
background:radial-gradient(circle,#c8b27a,#8b7440)}
|
| 91 |
+
#board{width:100%;height:auto;max-height:80vh;display:block}
|
| 92 |
+
#banner{position:absolute;left:50%;top:8px;transform:translateX(-50%);z-index:3;max-width:92%;min-width:240px;
|
| 93 |
+
background:rgba(25,15,8,.92);color:var(--cream);border:2px solid var(--gold);border-radius:10px;padding:6px 14px;text-align:center;
|
| 94 |
+
font-size:14px;box-shadow:0 3px 10px rgba(0,0,0,.6);pointer-events:none}
|
| 95 |
+
#banner b{color:var(--gold)}
|
| 96 |
+
#banner .l2{color:#ffd54a;font-weight:700}
|
| 97 |
+
#banner .dot,.dot{display:inline-block;width:12px;height:12px;border-radius:50%;margin-right:6px;border:1px solid #000;vertical-align:middle}
|
| 98 |
+
@keyframes pulse{0%,100%{opacity:.35}50%{opacity:1}}
|
| 99 |
+
@keyframes pop{0%{transform:scale(1.7);opacity:0}60%{transform:scale(.9);opacity:1}100%{transform:scale(1)}}
|
| 100 |
+
.pop{animation:pop .45s ease-out;transform-box:fill-box;transform-origin:center}
|
| 101 |
+
.pulse{animation:pulse .9s infinite}
|
| 102 |
+
.march{stroke-dasharray:9 6;animation:march .6s linear infinite}
|
| 103 |
+
@keyframes march{to{stroke-dashoffset:-15}}
|
| 104 |
+
.cell.legal{cursor:pointer}
|
| 105 |
+
|
| 106 |
+
/* maos e paineis inferiores */
|
| 107 |
+
.pw{display:flex;gap:6px;margin:5px 0;padding:4px 5px;border-radius:7px;background:rgba(0,0,0,.28);border:2px solid transparent;align-items:flex-start;min-height:34px}
|
| 108 |
+
.pw .tk{flex:0 0 22px;height:22px;border-radius:50%;background:#120c07;border:2px solid #5a4630;margin-top:1px;
|
| 109 |
+
display:flex;align-items:center;justify-content:center;font-size:13px;color:#000}
|
| 110 |
+
.pw.on .tk{border-color:#fff}
|
| 111 |
+
.pw.on{background:rgba(217,169,58,.2)}
|
| 112 |
+
.pw.legal{border-color:var(--ok);cursor:pointer;box-shadow:0 0 9px rgba(0,230,118,.55)}
|
| 113 |
+
.pw.legal:hover{background:rgba(0,230,118,.2)}
|
| 114 |
+
.pw.picked{border-color:#ffd54a;background:rgba(255,213,74,.28)}
|
| 115 |
+
.pw b{font:700 11.5px var(--serif);color:var(--gold);display:block}
|
| 116 |
+
.pw span{font-size:10.5px;opacity:.88;line-height:1.2;display:block}
|
| 117 |
+
.lvls{display:grid;grid-template-columns:repeat(3,1fr);gap:7px}
|
| 118 |
+
.lvls h3{margin:0 0 2px;font:700 11px var(--serif);color:#e6cf92;text-align:center;border-bottom:1px solid #7a5a28}
|
| 119 |
+
.abil{background:rgba(0,0,0,.3);border:1px solid #7a5a28;border-radius:7px;padding:5px 8px;margin:4px 0 6px;font-size:12px}
|
| 120 |
+
.abil b{color:var(--gold);font-family:var(--serif)}
|
| 121 |
+
.pool{display:flex;gap:4px;margin-top:5px;align-items:center;flex-wrap:wrap}
|
| 122 |
+
.ankhtk{display:inline-flex;width:22px;height:22px;border-radius:50%;align-items:center;justify-content:center;font-size:12px;color:#fff;border:2px solid #fff;text-shadow:0 1px 1px #000}
|
| 123 |
+
|
| 124 |
+
#handbox{margin:12px 0 0}
|
| 125 |
+
#hand{display:flex;gap:7px;flex-wrap:wrap;padding:16px 2px 4px;justify-content:center}
|
| 126 |
+
.bcard{width:108px;height:164px;border-radius:9px;border:3px solid #4a3010;background:linear-gradient(#f6ebc8,#dcc48a);
|
| 127 |
+
position:relative;box-shadow:0 4px 8px rgba(0,0,0,.55);transition:transform .15s,box-shadow .15s;overflow:hidden;color:var(--ink)}
|
| 128 |
+
.bcard .ttl{height:26px;color:#fff;font:700 11px/26px var(--serif);text-align:center;padding-left:24px;text-shadow:0 1px 2px #000;letter-spacing:.3px;white-space:nowrap}
|
| 129 |
+
.bcard .bn{position:absolute;left:3px;top:2px;width:24px;height:24px;border-radius:50%;background:#1b120a;color:var(--gold);border:2px solid var(--gold);
|
| 130 |
+
font:700 12px/20px sans-serif;text-align:center}
|
| 131 |
+
.bcard .art{height:52px;text-align:center;font-size:34px;line-height:52px}
|
| 132 |
+
.bcard .tx{font-size:9.6px;line-height:1.22;padding:0 6px;color:#3a2a14}
|
| 133 |
+
.bcard.playable{cursor:pointer;box-shadow:0 0 0 3px var(--ok),0 6px 14px rgba(0,0,0,.6)}
|
| 134 |
+
.bcard.playable:hover{transform:translateY(-10px)}
|
| 135 |
+
.bcard.picked{transform:translateY(-18px);box-shadow:0 0 0 4px #ffd54a,0 0 18px #ffd54a}
|
| 136 |
+
.bcard.used{filter:grayscale(.85) brightness(.72)}
|
| 137 |
+
.bcard.used::after{content:'USADA';position:absolute;left:0;right:0;top:46%;text-align:center;font:700 14px var(--serif);color:#7a1f1f;transform:rotate(-14deg);letter-spacing:2px}
|
| 138 |
+
.bcard.rev{width:86px;height:128px}.bcard.rev .art{height:38px;font-size:26px;line-height:38px}.bcard.rev .tx{display:none}
|
| 139 |
+
|
| 140 |
+
#tray{position:sticky;top:0;z-index:30;padding:7px 16px;color:var(--cream);
|
| 141 |
+
background:linear-gradient(#3a2616,#2a1b10);border-bottom:3px solid var(--gold2);box-shadow:0 5px 14px rgba(0,0,0,.65)}
|
| 142 |
+
#tray .decin{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;max-width:1700px;margin:0 auto}
|
| 143 |
+
#tray .prompt{flex:1 1 260px;font-size:13.5px;min-width:200px}
|
| 144 |
+
#tray .ctl{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px}
|
| 145 |
+
#tray .acts{display:flex;flex-wrap:wrap;gap:6px}
|
| 146 |
+
#tray .conf{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:4px 10px;border:2px dashed var(--gold);border-radius:8px;background:rgba(255,213,74,.16)}
|
| 147 |
+
#tray .conf b{color:#ffe28a}
|
| 148 |
+
#tray input[type=range]{width:200px;accent-color:#d9a93a}
|
| 149 |
+
#tray .bidn{font:700 18px var(--serif);color:#ffe28a;min-width:30px;text-align:center}
|
| 150 |
+
#tray select{padding:5px 8px;background:#2f2418;border:2px solid #7a5a28;border-radius:6px;color:var(--cream);max-width:260px}
|
| 151 |
+
#status{font:700 13px var(--serif);padding:5px 12px;border-radius:8px;background:#5a4630;color:var(--cream);letter-spacing:.5px;white-space:nowrap}
|
| 152 |
+
#status.me{background:#1f6b3a;color:#e5ffee;box-shadow:0 0 12px rgba(0,230,118,.5)}
|
| 153 |
+
#status.end{background:#7a1f1f}
|
| 154 |
+
#log{height:230px;overflow:auto;font:11.5px/1.4 ui-monospace,Consolas,monospace;background:rgba(0,0,0,.3);border-radius:7px;padding:6px;color:var(--cream)}
|
| 155 |
+
#log div.ev1{color:#ffd54a;font-weight:700}#log div.fim{color:#ff8a80;font-weight:700}#log div.me{color:#9dffc1}
|
| 156 |
+
#battle .row{display:flex;gap:6px;flex-wrap:wrap;justify-content:center}
|
| 157 |
+
#battle .who{text-align:center;font-size:11px;color:var(--cream)}
|
| 158 |
+
#modal,#endov{position:fixed;inset:0;background:rgba(0,0,0,.75);display:none;align-items:center;justify-content:center;z-index:20}
|
| 159 |
+
.box{background:linear-gradient(145deg,var(--parch1),var(--parch2));border:4px solid var(--gold2);border-radius:14px;padding:20px;width:min(430px,92vw);
|
| 160 |
+
box-shadow:0 10px 30px rgba(0,0,0,.8)}
|
| 161 |
+
.box h2{margin:0 0 6px;font:700 20px var(--serif);color:#7b3f12;letter-spacing:2px}
|
| 162 |
+
.box label{display:block;margin:10px 0 3px;font-weight:600}
|
| 163 |
+
.box select,.box input{width:100%;padding:6px;background:#fbf3d9;border:2px solid var(--gold2);border-radius:6px;color:var(--ink)}
|
| 164 |
+
.warn{background:#8a6a1c;color:#fff;border-radius:6px;padding:6px 10px;margin:8px 14px 0;font-size:12.5px}
|
| 165 |
+
</style>
|
| 166 |
+
</head>
|
| 167 |
+
<body>
|
| 168 |
+
<header>
|
| 169 |
+
<h1>☥ ANKH</h1><span class="meta" id="meta"></span><span class="sp"></span>
|
| 170 |
+
<span class="hdrlab">Velocidade</span>
|
| 171 |
+
<select id="speed" class="sel"><option value="1800">Lenta</option><option value="1000" selected>Normal</option><option value="450">Rápida</option><option value="0">Instantânea</option></select>
|
| 172 |
+
<button class="btn dark sm" id="bpause">⏸ Pausar</button>
|
| 173 |
+
<button class="btn dark sm" id="bstep" disabled>⏭ Passo</button>
|
| 174 |
+
<button class="btn dark sm" id="bskip">⏩ Pular</button>
|
| 175 |
+
<label class="hdrlab"><input type="checkbox" id="coords"> coordenadas</label>
|
| 176 |
+
<button class="btn" id="btnnew">Nova partida</button>
|
| 177 |
+
</header>
|
| 178 |
+
<div id="tray"><div class="decin"><div id="status">Carregando…</div></div></div>
|
| 179 |
+
<div id="warn"></div>
|
| 180 |
+
<div id="opps"></div>
|
| 181 |
+
<div id="table">
|
| 182 |
+
<div id="leftcol">
|
| 183 |
+
<div class="dark" id="dash"></div>
|
| 184 |
+
<div class="dark" id="god"></div>
|
| 185 |
+
</div>
|
| 186 |
+
<div id="centercol">
|
| 187 |
+
<div id="boardframe"><div id="banner"></div><svg id="board" xmlns="http://www.w3.org/2000/svg"></svg></div>
|
| 188 |
+
<div class="parch" id="handbox"><h2>Suas cartas de batalha</h2><div id="hand"></div></div>
|
| 189 |
+
</div>
|
| 190 |
+
<div id="rightcol">
|
| 191 |
+
<div class="dark"><h2>Devoção</h2><div id="devo"></div></div>
|
| 192 |
+
<div class="dark" id="battlebox" style="display:none"><h2>Batalha em andamento</h2><div id="battle"></div></div>
|
| 193 |
+
<div class="dark"><h2>Registro</h2><div id="log"></div></div>
|
| 194 |
+
</div>
|
| 195 |
+
</div>
|
| 196 |
+
<div id="modal"><div class="box">
|
| 197 |
+
<h2>Nova partida</h2>
|
| 198 |
+
<label>Cenário</label><select id="f_sc"></select>
|
| 199 |
+
<label>Seu assento (J0 joga primeiro)</label><select id="f_seat"></select>
|
| 200 |
+
<label>Seu deus</label><select id="f_god"></select>
|
| 201 |
+
<label>IA dos outros jogadores</label><select id="f_ai"></select>
|
| 202 |
+
<label>Seed (opcional)</label><input id="f_seed" placeholder="aleatória">
|
| 203 |
+
<div style="margin-top:16px;display:flex;gap:8px;justify-content:flex-end">
|
| 204 |
+
<button class="btn dark" id="f_cancel">Cancelar</button><button class="btn" id="f_go">Jogar</button>
|
| 205 |
+
</div>
|
| 206 |
+
</div></div>
|
| 207 |
+
<div id="endov"><div class="box" style="text-align:center"><h2 id="endt"></h2><p id="endp"></p>
|
| 208 |
+
<button class="btn" onclick="document.getElementById('endov').style.display='none'">Ver o tabuleiro</button>
|
| 209 |
+
<button class="btn" onclick="openModal()">Nova partida</button></div></div>
|
| 210 |
+
|
| 211 |
+
<script>
|
| 212 |
+
"use strict";
|
| 213 |
+
let B = null, S = null, OPT = null, LOG = [], FRAME = null, SEL = null, HOVER = null, busy = false, ENDSHOWN = null;
|
| 214 |
+
const PLAY = {on: false, paused: false, skip: false, wake: null};
|
| 215 |
+
const SZ = 30;
|
| 216 |
+
const GOD_COL = ['#d9534f', '#8e7cc3', '#4fb3d9', '#6aa84f', '#f0a030'];
|
| 217 |
+
const GOD_PT = ['Amun', 'Anubis', 'Ísis', 'Osíris', 'Rá'];
|
| 218 |
+
const GOD_ABILITY = [
|
| 219 |
+
['Mysterious Forms', 'Em 1 batalha por Conflito, joga 2 cartas de batalha (anuncie antes dos outros escolherem).'],
|
| 220 |
+
['Judge of the Dead', 'Guerreiros inimigos mortos podem ser presos aqui: +1 de força por preso (máx. +3).'],
|
| 221 |
+
['Protectress', 'Figuras suas adjacentes a inimigos ficam Protegidas: podem sobreviver à resolução da batalha.'],
|
| 222 |
+
['Gateway to the Underworld', 'Ao perder uma batalha, coloca/realoca um token Underworld. Invoca neles; inimigos não terminam ali.'],
|
| 223 |
+
['Radiance', 'Ao invocar, pode pôr um Sol na figura (Radiante): +1 Devoção ao vencer/dominar na região.']];
|
| 224 |
+
const KIND_ABBR = {1: 'D', 2: 'g', 3: 'Mu', 4: 'Sa', 5: 'Ap', 6: 'Es', 7: 'Af', 8: 'Gm'};
|
| 225 |
+
const KIND_PT = {1: 'Deus', 2: 'Guerreiro', 3: 'Mummy', 4: 'Satet', 5: 'Apep', 6: 'Giant Scorpion', 7: 'Androsphinx', 8: 'Cat-Mummy'};
|
| 226 |
+
const MON_PT = ['Obelisco', 'Templo', 'Pirâmide'];
|
| 227 |
+
const CARD_PT = [
|
| 228 |
+
['Plague of Locusts', '+1', '🦗', '#7a1f1f', 'Lance cego de Seguidores (todos pagam). Figuras morrem, exceto as de quem apostou mais.'],
|
| 229 |
+
['Build Monument', '+0', '🏛', '#6b4a1f', 'Pague 3 Seguidores e construa um Monumento numa casa vazia da região.'],
|
| 230 |
+
['Chariots', '+3', '🐎', '#3d4a5a', 'Apenas +3 de força.'],
|
| 231 |
+
["Cycle of Ma'at", '+0', '🪶', '#5a3d7a', 'Depois da batalha, recupera todas as suas cartas usadas.'],
|
| 232 |
+
['Drought', '+1', '☀', '#a8761a', 'Se vencer: +1 Devoção por figura sua em deserto na região.'],
|
| 233 |
+
['Flood', '+0', '🌊', '#1f5f8a', 'Ganha 1 Seguidor por figura sua em terra fértil; elas não morrem na resolução.'],
|
| 234 |
+
['Miracle', '+0', '✨', '#9a7e12', 'Depois da resolução: +1 Devoção por figura sua morta na batalha.']];
|
| 235 |
+
const POWER_PT = [
|
| 236 |
+
['Commanding', 'Vence batalha: +3 Seguidores.'],
|
| 237 |
+
['Inspiring', 'Build Monument sai de graça.'],
|
| 238 |
+
['Omnipresent', 'Início de Conflito: +1 Seguidor por região com figura sua.'],
|
| 239 |
+
['Revered', 'Ganhar Seguidores: +1 extra.'],
|
| 240 |
+
['Resplendent', 'Com 3+ Monumentos iguais, o Deus tem força base 3.'],
|
| 241 |
+
['Obelisk Attuned', 'Início de batalha: leve figuras a casas ao lado dos seus Obeliscos.'],
|
| 242 |
+
['Temple Attuned', 'Cada Templo seu: +2 de força se há figura sua adjacente.'],
|
| 243 |
+
['Pyramid Attuned', 'Invocar: +1 figura adjacente a cada Pirâmide sua.'],
|
| 244 |
+
['Glorious', 'Vence por 3+ de margem: 3 Devoção em vez de 1.'],
|
| 245 |
+
['Magnanimous', 'Perde com 2+ figuras: +2 Devoção.'],
|
| 246 |
+
['Bountiful', 'Na zona vermelha: +1 Devoção extra por ganho.'],
|
| 247 |
+
['Worshipful', 'Após batalha: 2 Seguidores → 1 Devoção.']];
|
| 248 |
+
const ACT_PT = [['Mover figuras', '👣'], ['Invocar figura', '🏺'], ['Ganhar seguidores', '👥'], ['Desbloquear poder', '☥']];
|
| 249 |
+
const PROMPT = {
|
| 250 |
+
CHOOSE_ACTION: 'Escolha uma ação no painel central (a 2ª ação precisa estar numa linha mais baixa que a 1ª).',
|
| 251 |
+
MOVE_SELECT: 'Clique numa figura sua para movê-la (até 3 casas), ou termine o movimento.',
|
| 252 |
+
MOVE_DEST: 'Clique no destino (clique na casa de origem para deixar a figura onde está).',
|
| 253 |
+
SUMMON_TYPE: 'O que você quer invocar?',
|
| 254 |
+
SUMMON_DEST: 'Clique na casa onde a figura será colocada.',
|
| 255 |
+
UNLOCK_PICK: 'Escolha o poder Ankh a desbloquear (no painel do seu deus).',
|
| 256 |
+
AMUN_DECLARE: 'Amun: anunciar que jogará 2 cartas nesta batalha?',
|
| 257 |
+
CLAW_POINT: 'Giant Scorpion: escolha a orientação das garras.',
|
| 258 |
+
PUSH_DEST: 'Satet: para onde empurrar o inimigo?',
|
| 259 |
+
UNDERWORLD_SRC: 'Underworld: qual token realocar?',
|
| 260 |
+
UNDERWORLD_DEST: 'Underworld: clique na casa para o token.',
|
| 261 |
+
ATTUNE_SRC: 'Obelisk Attuned: clique numa figura para levá-la a um Obelisco.',
|
| 262 |
+
ATTUNE_DEST: 'Obelisk Attuned: clique na casa de destino.',
|
| 263 |
+
WORSHIP: 'Worshipful: sacrificar 2 Seguidores por 1 Devoção?',
|
| 264 |
+
CONTROL_PICK: 'Controlar Monumento: clique no Monumento que você quer controlar.',
|
| 265 |
+
CAMEL_LINE: 'Caravana de Camelos: escolha a linha (o tabuleiro mostra a prévia).',
|
| 266 |
+
CAMEL_KEEP: 'Qual das duas novas regiões mantém o token de ordem do Conflito antigo?',
|
| 267 |
+
CAMEL_SWAP: 'Quer trocar um token de ordem do Conflito?',
|
| 268 |
+
BATTLE_CARD: 'Batalha! Escolha sua carta (em segredo) clicando nela.',
|
| 269 |
+
BUILD_TYPE: 'Build Monument: construir qual Monumento?',
|
| 270 |
+
BUILD_CELL: 'Clique na casa vazia onde construir.',
|
| 271 |
+
BID: 'Plague of Locusts: quantos Seguidores você aposta? (todos pagam o lance)',
|
| 272 |
+
TIEBREAK: 'Empate na batalha: usar o token de desempate?'
|
| 273 |
+
};
|
| 274 |
+
const TER = {F: 'url(#pF)', D: 'url(#pD)', W: 'url(#pW)'};
|
| 275 |
+
|
| 276 |
+
const $ = id => document.getElementById(id);
|
| 277 |
+
const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
| 278 |
+
const cap = s => s.charAt(0).toUpperCase() + s.slice(1);
|
| 279 |
+
const setHTML = (id, h) => { $(id).innerHTML = h; };
|
| 280 |
+
const cellOf = i => (S.cells && S.cells[i]) || {};
|
| 281 |
+
const gcol = seat => (S.players[seat] ? GOD_COL[S.players[seat].god] : '#888');
|
| 282 |
+
|
| 283 |
+
// ---------- geometria ----------
|
| 284 |
+
function cxy(i) { const c = B.cells[i]; return {x: 40 + c.col * 1.5 * SZ, y: 40 + c.r2 * (Math.sqrt(3) / 2) * SZ}; }
|
| 285 |
+
function hexPts(x, y, k) {
|
| 286 |
+
const s = SZ * (k || 1), p = [];
|
| 287 |
+
for (let n = 0; n < 6; n++) { const a = Math.PI / 3 * n; p.push((x + s * Math.cos(a)).toFixed(1) + ',' + (y + s * Math.sin(a)).toFixed(1)); }
|
| 288 |
+
return p.join(' ');
|
| 289 |
+
}
|
| 290 |
+
function edgeSeg(i, j) {
|
| 291 |
+
const a = cxy(i), b = cxy(j), mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
|
| 292 |
+
let dx = b.x - a.x, dy = b.y - a.y; const L = Math.hypot(dx, dy) || 1; dx /= L; dy /= L;
|
| 293 |
+
const h = SZ / 2;
|
| 294 |
+
return [mx + dy * h, my - dx * h, mx - dy * h, my + dx * h].map(v => v.toFixed(1));
|
| 295 |
+
}
|
| 296 |
+
const lineEl = (s, st, w, ex) => `<line x1="${s[0]}" y1="${s[1]}" x2="${s[2]}" y2="${s[3]}" stroke="${st}" stroke-width="${w}" stroke-linecap="round" ${ex || ''}/>`;
|
| 297 |
+
|
| 298 |
+
// ---------- tabuleiro ----------
|
| 299 |
+
const DEFS = `<defs>
|
| 300 |
+
<pattern id="pF" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="10" height="10" fill="#86b25f"/><path d="M1 8 L2 5 M5 9 L6 6 M8 4 L9 1" stroke="#6f9b4a" stroke-width="1.2"/></pattern>
|
| 301 |
+
<pattern id="pD" width="9" height="9" patternUnits="userSpaceOnUse"><rect width="9" height="9" fill="#e6cd8c"/><circle cx="2" cy="2" r=".9" fill="#d3b672"/><circle cx="6.5" cy="6" r=".9" fill="#d3b672"/></pattern>
|
| 302 |
+
<pattern id="pW" width="14" height="8" patternUnits="userSpaceOnUse"><rect width="14" height="8" fill="#74aadb"/><path d="M0 5 Q3.5 2 7 5 T14 5" fill="none" stroke="#9cc6ea" stroke-width="1.1"/></pattern>
|
| 303 |
+
<filter id="sh" x="-30%" y="-30%" width="160%" height="170%"><feDropShadow dx="0" dy="2" stdDeviation="1.6" flood-color="#000" flood-opacity=".55"/></filter>
|
| 304 |
+
<marker id="arr" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10 z" fill="#fff"/></marker>
|
| 305 |
+
</defs>`;
|
| 306 |
+
function monSVG(kind, x, y) {
|
| 307 |
+
const st = 'stroke="#2a2118" stroke-width="1.6"';
|
| 308 |
+
if (kind === 0) return `<polygon points="${x - 5},${y + 14} ${x - 5},${y - 6} ${x},${y - 17} ${x + 5},${y - 6} ${x + 5},${y + 14}" fill="#f0dc9a" ${st}/><line x1="${x}" y1="${y - 14}" x2="${x}" y2="${y + 12}" stroke="#c9a85a"/>`;
|
| 309 |
+
if (kind === 1) return `<rect x="${x - 14}" y="${y - 6}" width="28" height="18" fill="#f0dc9a" ${st}/><polygon points="${x - 17},${y - 6} ${x},${y - 16} ${x + 17},${y - 6}" fill="#d6bd72" ${st}/>` +
|
| 310 |
+
[-7, 0, 7].map(d => `<line x1="${x + d}" y1="${y - 4}" x2="${x + d}" y2="${y + 10}" stroke="#2a2118" stroke-width="1.6"/>`).join('');
|
| 311 |
+
return `<polygon points="${x},${y - 17} ${x + 17},${y + 12} ${x - 17},${y + 12}" fill="#f0dc9a" ${st}/><line x1="${x}" y1="${y - 17}" x2="${x}" y2="${y + 12}" stroke="#c9a85a"/>`;
|
| 312 |
+
}
|
| 313 |
+
function figSVG(f, x, y, popin) {
|
| 314 |
+
const col = gcol(f[0]), k = f[1];
|
| 315 |
+
const r = k === 1 ? SZ * 0.6 : (k === 2 ? SZ * 0.4 : SZ * 0.5);
|
| 316 |
+
const lab = k === 1 ? GOD_PT[S.players[f[0]].god].slice(0, 2) : KIND_ABBR[k];
|
| 317 |
+
let s = `<g filter="url(#sh)" ${popin ? 'class="pop"' : ''}><circle cx="${x}" cy="${y}" r="${r}" fill="${col}" stroke="${k === 1 ? '#fff6d0' : '#1b120a'}" stroke-width="${k === 1 ? 3.2 : 2}"/>`;
|
| 318 |
+
s += `<circle cx="${x}" cy="${y}" r="${r * 0.72}" fill="none" stroke="rgba(255,255,255,.35)" stroke-width="1.2"/>`;
|
| 319 |
+
s += `<text x="${x}" y="${y + 4}" text-anchor="middle" font-size="${k === 1 ? 12.5 : 11}" font-weight="700" fill="#fff" style="paint-order:stroke;stroke:#000;stroke-width:2.2px;pointer-events:none">${esc(lab)}</text>`;
|
| 320 |
+
if (f[2]) s += `<circle cx="${x + r * 0.78}" cy="${y - r * 0.78}" r="5.5" fill="#ffd400" stroke="#7a5a00"/>`;
|
| 321 |
+
return s + '</g>';
|
| 322 |
+
}
|
| 323 |
+
function cellTitle(i) {
|
| 324 |
+
const c = cellOf(i), b = B.cells[i];
|
| 325 |
+
const p = [`(${b.col},${b.line}) ${b.ter === 'W' ? 'água' : b.ter === 'F' ? 'terra fértil' : 'deserto'}`];
|
| 326 |
+
if (c.f) p.push(`${KIND_PT[c.f[1]]} de J${c.f[0]} (${GOD_PT[S.players[c.f[0]].god]})${c.f[2] ? ' – Radiante' : ''}`);
|
| 327 |
+
if (c.m) p.push(`${MON_PT[c.m[0]]} ${c.m[1] >= 0 ? 'de J' + c.m[1] : 'neutro'}`);
|
| 328 |
+
if (c.u) p.push('Underworld');
|
| 329 |
+
return p.join(' | ');
|
| 330 |
+
}
|
| 331 |
+
function boardSVG() {
|
| 332 |
+
const D = S.decision, legal = {};
|
| 333 |
+
if (D) D.actions.forEach(a => { if (a.cell !== undefined) legal[a.cell] = a; });
|
| 334 |
+
const inReg = {}; (S.cur_region || []).forEach(i => inReg[i] = 1);
|
| 335 |
+
const hv = HOVER || {}, hvc = {};
|
| 336 |
+
(hv.region || []).forEach(i => hvc[i] = 1);
|
| 337 |
+
(hv.regions || []).forEach((r, k) => r.forEach(i => hvc[i] = k + 1));
|
| 338 |
+
const hl = (FRAME && FRAME.hl) || {};
|
| 339 |
+
const actorCol = FRAME ? gcol(FRAME.actor) : '#fff';
|
| 340 |
+
let g = DEFS, maxx = 0, maxy = 0;
|
| 341 |
+
for (const c of B.cells) {
|
| 342 |
+
const p = cxy(c.i); maxx = Math.max(maxx, p.x); maxy = Math.max(maxy, p.y);
|
| 343 |
+
g += `<polygon class="cell${legal[c.i] ? ' legal' : ''}" points="${hexPts(p.x, p.y)}" fill="${TER[c.ter]}" stroke="#5d4a28" stroke-width="1.1"><title>${esc(cellTitle(c.i))}</title></polygon>`;
|
| 344 |
+
if (inReg[c.i]) g += `<polygon points="${hexPts(p.x, p.y)}" fill="rgba(255,213,74,.26)" stroke="none" pointer-events="none"/>`;
|
| 345 |
+
if (hvc[c.i]) g += `<polygon points="${hexPts(p.x, p.y)}" fill="${hvc[c.i] === 2 ? 'rgba(255,0,170,.38)' : 'rgba(0,200,255,.38)'}" stroke="none" pointer-events="none"/>`;
|
| 346 |
+
}
|
| 347 |
+
for (const [i, j] of B.river) g += lineEl(edgeSeg(i, j), '#2a6fc9', 5.5, 'pointer-events="none"') + lineEl(edgeSeg(i, j), '#7fb6ee', 2, 'pointer-events="none"');
|
| 348 |
+
for (const [i, j] of S.camels) g += lineEl(edgeSeg(i, j), '#5a3210', 6.5, 'pointer-events="none"') + lineEl(edgeSeg(i, j), '#b8803a', 2.5, 'pointer-events="none"');
|
| 349 |
+
const edgesPrev = hv.edges || hl.edges;
|
| 350 |
+
if (edgesPrev) for (const [i, j] of edgesPrev) g += lineEl(edgeSeg(i, j), '#ff2fa8', 6, 'pointer-events="none" class="pulse"');
|
| 351 |
+
if (hl.from !== null && hl.from !== undefined) { const p = cxy(hl.from); g += `<circle cx="${p.x}" cy="${p.y}" r="${SZ * 0.55}" fill="${actorCol}" fill-opacity=".25" stroke="${actorCol}" stroke-width="2.5" stroke-dasharray="4 3" pointer-events="none"/>`; }
|
| 352 |
+
for (const k of Object.keys(S.cells || {})) {
|
| 353 |
+
const i = +k, c = S.cells[k], p = cxy(i);
|
| 354 |
+
if (c.u && !c.f) g += `<circle cx="${p.x}" cy="${p.y}" r="${SZ * 0.55}" fill="rgba(40,10,60,.6)" stroke="#c7b3f0" stroke-dasharray="3 2" pointer-events="none"/>`;
|
| 355 |
+
if (c.m) {
|
| 356 |
+
g += `<g filter="url(#sh)" ${hl.to === i ? 'class="pop"' : ''}>` + monSVG(c.m[0], p.x, p.y);
|
| 357 |
+
if (c.m[1] >= 0) g += `<circle cx="${p.x + 16}" cy="${p.y + 14}" r="6.5" fill="${gcol(c.m[1])}" stroke="#fff" stroke-width="1.6"/><text x="${p.x + 16}" y="${p.y + 17.5}" text-anchor="middle" font-size="9" fill="#fff" font-weight="700" pointer-events="none">☥</text>`;
|
| 358 |
+
g += '</g>';
|
| 359 |
+
}
|
| 360 |
+
if (c.f) g += figSVG(c.f, p.x, p.y, hl.to === i);
|
| 361 |
+
if (c.cl) c.cl.forEach(j => { const q = cxy(j); g += `<circle cx="${q.x}" cy="${q.y}" r="${SZ * 0.72}" fill="none" stroke="#d32f2f" stroke-width="2.5" stroke-dasharray="4 3" pointer-events="none"/>`; });
|
| 362 |
+
}
|
| 363 |
+
if (hl.from !== null && hl.from !== undefined && hl.to !== null && hl.to !== undefined) {
|
| 364 |
+
const a = cxy(hl.from), b = cxy(hl.to);
|
| 365 |
+
g += `<line x1="${a.x}" y1="${a.y}" x2="${b.x}" y2="${b.y}" stroke="${actorCol}" stroke-width="5" opacity=".9" pointer-events="none" class="march" marker-end="url(#arr)"/>`;
|
| 366 |
+
}
|
| 367 |
+
if (hl.to !== null && hl.to !== undefined && !(hl.from !== null && hl.from !== undefined)) { const p = cxy(hl.to); g += `<circle cx="${p.x}" cy="${p.y}" r="${SZ * 0.82}" fill="none" stroke="${actorCol}" stroke-width="3.5" class="pulse" pointer-events="none"/>`; }
|
| 368 |
+
else if (hl.to !== null && hl.to !== undefined) { const p = cxy(hl.to); g += `<circle cx="${p.x}" cy="${p.y}" r="${SZ * 0.82}" fill="none" stroke="#fff" stroke-width="3" class="pulse" pointer-events="none"/>`; }
|
| 369 |
+
for (const [i, t] of S.tokens) {
|
| 370 |
+
const p = cxy(i), x = p.x - SZ * 0.62, y = p.y - SZ * 0.58;
|
| 371 |
+
g += `<g pointer-events="none"><circle cx="${x}" cy="${y}" r="9.5" fill="#1b120a" stroke="#ffd54a" stroke-width="1.6"/><text x="${x}" y="${y + 4.2}" text-anchor="middle" font-size="12" font-weight="700" fill="#ffd54a">${t}</text></g>`;
|
| 372 |
+
}
|
| 373 |
+
if (D && D.src !== null && D.src !== undefined) { const p = cxy(D.src); g += `<polygon points="${hexPts(p.x, p.y)}" fill="none" stroke="#ffeb3b" stroke-width="4" pointer-events="none"/>`; }
|
| 374 |
+
for (const k of Object.keys(legal)) {
|
| 375 |
+
const p = cxy(+k);
|
| 376 |
+
g += `<polygon points="${hexPts(p.x, p.y)}" fill="rgba(0,230,118,.22)" stroke="#00e676" stroke-width="3" class="pulse" style="cursor:pointer" onclick="act(${legal[k].a})"><title>${esc(legal[k].text)}</title></polygon>`;
|
| 377 |
+
}
|
| 378 |
+
if ($('coords') && $('coords').checked) for (const c of B.cells) { const p = cxy(c.i); g += `<text x="${p.x}" y="${p.y + SZ * 0.84}" text-anchor="middle" font-size="9" fill="#222" pointer-events="none">${c.col},${c.line}</text>`; }
|
| 379 |
+
return {html: g, w: maxx + 50, h: maxy + 50};
|
| 380 |
+
}
|
| 381 |
+
function renderBoard() {
|
| 382 |
+
const b = boardSVG(), svg = $('board');
|
| 383 |
+
svg.setAttribute('viewBox', `0 0 ${b.w} ${b.h}`);
|
| 384 |
+
svg.innerHTML = b.html;
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
// ---------- painel central: ações + eventos ----------
|
| 388 |
+
function renderDash() {
|
| 389 |
+
const D = S.decision, legalLine = {};
|
| 390 |
+
if (D && D.phase === 'CHOOSE_ACTION') D.actions.forEach((a, idx) => { legalLine[a.a] = idx; });
|
| 391 |
+
const st = B.action_start[S.P];
|
| 392 |
+
let h = `<h2>Painel central</h2><div class="hint" style="margin-bottom:4px">Vez de <b>J${S.cur}</b> (${S.players[S.cur] ? GOD_PT[S.players[S.cur].god] : ''})</div>`;
|
| 393 |
+
for (let l = 0; l < 4; l++) {
|
| 394 |
+
const lg = legalLine[l] !== undefined, picked = SEL && SEL.a === l && lg;
|
| 395 |
+
const fl = FRAME && FRAME.hl && FRAME.hl.line === l;
|
| 396 |
+
h += `<div class="arow ${lg ? 'legal' : ''} ${picked ? 'picked' : ''} ${fl ? 'flash' : ''}" ${lg ? `onclick="sel(${legalLine[l]})"` : ''} title="${ACT_PT[l][0]}"><b>${ACT_PT[l][1]} ${ACT_PT[l][0]}</b>`;
|
| 397 |
+
for (let k = 0; k <= B.action_end; k++) h += `<i class="slot ${k < st ? 'off' : ''} ${k === B.action_end ? 'end' : ''} ${k === S.markers[l] ? 'mk' : ''}"></i>`;
|
| 398 |
+
h += '</div>';
|
| 399 |
+
}
|
| 400 |
+
h += '<div class="evnote">O marcador anda 1 casa a cada ação. Na casa "!" a ação dispara o próximo evento.</div>';
|
| 401 |
+
let ord = 0;
|
| 402 |
+
const rows = [B.events.slice(0, 6), B.events.slice(6, 12), B.events.slice(12, 18)];
|
| 403 |
+
h += '<h2 style="margin-top:10px">Linha do tempo</h2>';
|
| 404 |
+
rows.forEach((row, r) => {
|
| 405 |
+
const cells = row.map((k, c) => ({k, i: r * 6 + c, ord: k === 'conf' ? null : 0}));
|
| 406 |
+
h += '<div class="evgrid">';
|
| 407 |
+
const ordered = r % 2 === 1 ? cells.slice().reverse() : cells;
|
| 408 |
+
ordered.forEach(e => {
|
| 409 |
+
let o = 0; B.events.slice(0, e.i + 1).forEach(x => { if (x === 'conf') o++; });
|
| 410 |
+
const ic = e.k === 'ctrl' ? '▲' : e.k === 'camel' ? '🐪' : '⚔';
|
| 411 |
+
const nm = e.k === 'ctrl' ? 'Controlar Monumento' : e.k === 'camel' ? 'Caravana de Camelos' : 'Conflito ' + o;
|
| 412 |
+
h += `<div class="ev ${e.k} ${e.i < S.event_idx ? 'done' : ''} ${e.i === S.event_idx ? 'next' : ''} ${e.i === S.event_idx - 1 ? 'cur' : ''}" title="${nm}">${ic}${e.k === 'conf' ? '<small>C' + o + '</small>' : ''}</div>`;
|
| 413 |
+
});
|
| 414 |
+
h += '</div>';
|
| 415 |
+
});
|
| 416 |
+
h += '<div class="evnote">⚔ Conflito · 🐪 Camelos · ▲ Controlar Monumento.<br>C3: os 2 últimos deuses se fundem (3+ jogadores). C4: deuses na zona vermelha são esquecidos. Vence quem chegar ao topo da Devoção.</div>';
|
| 417 |
+
setHTML('dash', h);
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
// ---------- tabuleiro de devoção ----------
|
| 421 |
+
function renderDevo() {
|
| 422 |
+
const W = 262, rowH = 50, rows = 8, H = rows * rowH + 46;
|
| 423 |
+
const pos = k => { const r = Math.floor(k / 4); let c = k % 4; if (r % 2) c = 3 - c; return {x: 48 + c * 56, y: H - 40 - r * rowH}; };
|
| 424 |
+
let s = `<svg viewBox="0 0 ${W} ${H}" style="width:100%;height:auto"><defs><radialGradient id="gR" cx=".35" cy=".3"><stop offset="0" stop-color="#e86a4a"/><stop offset="1" stop-color="#7a1f10"/></radialGradient><radialGradient id="gB" cx=".35" cy=".3"><stop offset="0" stop-color="#6fa8e8"/><stop offset="1" stop-color="#1f4f8a"/></radialGradient><radialGradient id="gG" cx=".35" cy=".3"><stop offset="0" stop-color="#fff2a8"/><stop offset="1" stop-color="#c9951c"/></radialGradient></defs>`;
|
| 425 |
+
let path = ''; for (let k = 0; k <= B.top; k++) { const p = pos(k); path += (k ? 'L' : 'M') + p.x + ' ' + p.y; }
|
| 426 |
+
s += `<path d="${path}" fill="none" stroke="#c9a24a" stroke-width="3" opacity=".55"/>`;
|
| 427 |
+
for (let k = 0; k <= B.top; k++) {
|
| 428 |
+
const p = pos(k), top = k === B.top;
|
| 429 |
+
s += `<circle cx="${p.x}" cy="${p.y}" r="${top ? 20 : 17}" fill="url(#${top ? 'gG' : k < B.red ? 'gR' : 'gB'})" stroke="#e6cf92" stroke-width="2"/><text x="${p.x}" y="${p.y + 4}" text-anchor="middle" font-size="${top ? 17 : 10}" fill="#fff" opacity="${top ? 1 : .7}" style="pointer-events:none">${top ? '☥' : k}</text>`;
|
| 430 |
+
}
|
| 431 |
+
const stack = {};
|
| 432 |
+
for (const p of S.players) {
|
| 433 |
+
if (!p.alive) continue;
|
| 434 |
+
const q = pos(p.dev), n = (stack[p.dev] = (stack[p.dev] || 0) + 1) - 1;
|
| 435 |
+
const ox = (p.dev_order >= 0 ? p.dev_order : n) * 6 + (p.absorbed ? 9 : 0), oy = (p.dev_order >= 0 ? p.dev_order : n) * -6;
|
| 436 |
+
s += `<g><circle cx="${q.x + ox - 6}" cy="${q.y + oy - 2}" r="11" fill="${GOD_COL[p.god]}" stroke="${p.seat === S.human ? '#fff' : '#1b120a'}" stroke-width="${p.seat === S.human ? 3 : 2}" filter="drop-shadow(0 2px 2px rgba(0,0,0,.7))"/><text x="${q.x + ox - 6}" y="${q.y + oy + 2}" text-anchor="middle" font-size="9.5" font-weight="700" fill="#fff" style="paint-order:stroke;stroke:#000;stroke-width:1.8px">J${p.seat}</text></g>`;
|
| 437 |
+
}
|
| 438 |
+
s += '</svg><div class="hint">Vermelho: zona de risco (esquecido após o 4º Conflito). O token de cima da pilha tem mais Devoção.</div>';
|
| 439 |
+
setHTML('devo', s);
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
// ---------- oponentes ----------
|
| 443 |
+
function renderOpps() {
|
| 444 |
+
let h = '';
|
| 445 |
+
for (const p of S.players) {
|
| 446 |
+
if (p.seat === S.human) continue;
|
| 447 |
+
const tags = [];
|
| 448 |
+
if (!p.alive) tags.push('<span class="chip bad">esquecido</span>');
|
| 449 |
+
if (p.absorbed) tags.push(`<span class="chip warn">absorvido por J${p.ent}</span>`);
|
| 450 |
+
if (p.superior) tags.push(`<span class="chip warn">fundido com J${S.merged[1]}</span>`);
|
| 451 |
+
if (S.tiebreak_holder === p.seat && S.tiebreak_available) tags.push('<span class="chip">desempate</span>');
|
| 452 |
+
if (p.god === 4) tags.push(`<span class="chip">Sol ${p.sun_left}</span>`);
|
| 453 |
+
if (p.god === 3) tags.push(`<span class="chip">Underworld ${p.uw_off}</span>`);
|
| 454 |
+
if (p.god === 1) tags.push(`<span class="chip">presos ${p.trapped}/${S.anubis_slots}</span>`);
|
| 455 |
+
const pw = p.powers.map(k => `<span class="chip l${Math.floor(k / 4) + 1}" title="${esc(POWER_PT[k][0] + ': ' + POWER_PT[k][1])}">${POWER_PT[k][0]}</span>`).join('');
|
| 456 |
+
const usedSet = new Set(p.used);
|
| 457 |
+
const minis = CARD_PT.map((c, i) => `<span class="mini ${usedSet.has(i) ? 'used' : ''}" title="${esc(c[0])}${usedSet.has(i) ? ' (usada)' : ''}"></span>`).join('');
|
| 458 |
+
const gp = p.gpool.length ? ' · Guardiões: ' + p.gpool.map(k => KIND_PT[k]).join(', ') : '';
|
| 459 |
+
h += `<div class="opp ${S.cur === p.seat ? 'turn' : ''} ${p.alive ? '' : 'dead'}"><div class="hd" style="background:${GOD_COL[p.god]}">J${p.seat} · ${GOD_PT[p.god]}${p.god2 !== null && p.god2 !== undefined ? ' + ' + GOD_PT[p.god2] : ''}${S.cur === p.seat ? ' ◄ vez' : ''}</div>` +
|
| 460 |
+
`<div class="bd"><span class="stat">Devoção <b>${p.dev}</b></span><span class="stat">Seguidores <b>${p.followers}</b></span><span class="stat">Guerreiros <b>${p.board_w}</b>/${p.board_w + p.pool}</span><div>${tags.join('')}${pw}</div>` +
|
| 461 |
+
`<div style="margin-top:3px" title="Cartas de batalha: vermelhas = já usadas">${minis}</div><div class="hint">${esc(gp)}</div></div></div>`;
|
| 462 |
+
}
|
| 463 |
+
setHTML('opps', h);
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
// ---------- painel do seu deus ----------
|
| 467 |
+
function renderGod() {
|
| 468 |
+
const me = S.players[S.human], D = S.decision;
|
| 469 |
+
const legalPw = {};
|
| 470 |
+
if (D && D.phase === 'UNLOCK_PICK') D.actions.forEach((a, idx) => { legalPw[a.power] = idx; });
|
| 471 |
+
const ab = GOD_ABILITY[me.god];
|
| 472 |
+
let h = `<h2 style="color:${GOD_COL[me.god]}">${GOD_PT[me.god]}${me.god2 !== null && me.god2 !== undefined ? ' + ' + GOD_PT[me.god2] : ''} · você é J${S.human}</h2>`;
|
| 473 |
+
h += `<div class="abil"><b>${ab[0]}</b><br>${esc(ab[1])}</div>`;
|
| 474 |
+
const unlocked = new Set(me.powers);
|
| 475 |
+
h += '<div class="lvls">';
|
| 476 |
+
for (let l = 0; l < 3; l++) {
|
| 477 |
+
h += `<div><h3>Nível ${l + 1}</h3>`;
|
| 478 |
+
for (let k = l * 4; k < l * 4 + 4; k++) {
|
| 479 |
+
const on = unlocked.has(k), lg = legalPw[k] !== undefined, pk = SEL && SEL.power === k;
|
| 480 |
+
h += `<div class="pw ${on ? 'on' : ''} ${lg ? 'legal' : ''} ${pk ? 'picked' : ''}" ${lg ? `onclick="sel(${legalPw[k]})"` : ''} title="${esc(POWER_PT[k][1])}"><div class="tk" style="${on ? 'background:' + GOD_COL[me.god] : ''}">${on ? '☥' : ''}</div><div><b>${POWER_PT[k][0]}</b><span>${esc(POWER_PT[k][1])}</span></div></div>`;
|
| 481 |
+
}
|
| 482 |
+
h += '</div>';
|
| 483 |
+
}
|
| 484 |
+
h += '</div><div class="pool">';
|
| 485 |
+
const nxt = me.unlock_next;
|
| 486 |
+
for (let l = 0; l < 3; l++) {
|
| 487 |
+
const left = Math.max(0, 2 - Math.max(0, nxt - 2 * l));
|
| 488 |
+
const tk = `<span class="ankhtk" style="background:${GOD_COL[me.god]}">☥</span>`;
|
| 489 |
+
h += `<span class="hint">Nv${l + 1}:</span>` + tk.repeat(Math.min(2, left)) + (left === 0 ? '<span class="hint">✔</span>' : '');
|
| 490 |
+
h += ' ';
|
| 491 |
+
}
|
| 492 |
+
h += `</div><div class="hint" style="margin-top:6px"><span class="stat">Devoção <b>${me.dev}</b></span> <span class="stat">Seguidores <b>${me.followers}</b></span> <span class="stat">Guerreiros no mapa <b>${me.board_w}</b> / reserva <b>${me.pool}</b></span> <span class="stat">Tokens Ankh <b>${me.ankh}</b></span></div>`;
|
| 493 |
+
const extra = [];
|
| 494 |
+
if (me.god === 4) extra.push(`Sol restante: ${me.sun_left}`);
|
| 495 |
+
if (me.god === 3) extra.push(`Underworld fora do mapa: ${me.uw_off}`);
|
| 496 |
+
if (me.god === 1) extra.push(`Guerreiros presos: ${me.trapped}/${S.anubis_slots}`);
|
| 497 |
+
if (me.gpool.length) extra.push('Guardiões na reserva: ' + me.gpool.map(k => KIND_PT[k]).join(', '));
|
| 498 |
+
extra.push(`Guardiões em jogo: nv1 ${KIND_PT[S.g_card[1]]} (${S.g_supply[1]}), nv2 ${KIND_PT[S.g_card[2]]} (${S.g_supply[2]}), nv3 ${KIND_PT[S.g_card[3]]} (${S.g_supply[3]})`);
|
| 499 |
+
h += `<div class="hint" style="margin-top:4px">${esc(extra.join(' · '))}</div>`;
|
| 500 |
+
setHTML('god', h);
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
// ---------- cartas ----------
|
| 504 |
+
function cardHTML(c, cls, attrs) {
|
| 505 |
+
const k = CARD_PT[c];
|
| 506 |
+
return `<div class="bcard ${cls || ''}" ${attrs || ''} title="${esc(k[0] + ' (' + k[1] + '): ' + k[4])}"><div class="bn">${k[1]}</div><div class="ttl" style="background:${k[3]}">${esc(k[0].replace(' of Locusts', '').replace(" of Ma'at", ''))}</div><div class="art">${k[2]}</div><div class="tx">${esc(k[4])}</div></div>`;
|
| 507 |
+
}
|
| 508 |
+
function renderHand() {
|
| 509 |
+
const D = S.decision, me = S.players[S.human], inHand = new Set(S.hand), used = new Set(me.used);
|
| 510 |
+
const legal = {};
|
| 511 |
+
if (D && D.phase === 'BATTLE_CARD') D.actions.forEach((a, idx) => { legal[a.card] = idx; });
|
| 512 |
+
let h = '';
|
| 513 |
+
for (let c = 0; c < 7; c++) {
|
| 514 |
+
const lg = legal[c] !== undefined, pk = SEL && SEL.card === c;
|
| 515 |
+
h += cardHTML(c, `${lg ? 'playable' : ''} ${pk ? 'picked' : ''} ${inHand.has(c) ? '' : 'used'}`, lg ? `onclick="sel(${legal[c]})"` : '');
|
| 516 |
+
}
|
| 517 |
+
setHTML('hand', h);
|
| 518 |
+
}
|
| 519 |
+
function renderBattle() {
|
| 520 |
+
const box = $('battlebox');
|
| 521 |
+
if (!S.cur_region) { box.style.display = 'none'; return; }
|
| 522 |
+
box.style.display = 'block';
|
| 523 |
+
let h = '<div class="row">';
|
| 524 |
+
const cc = S.cur_cards || {};
|
| 525 |
+
const ks = Object.keys(cc).filter(e => cc[e].length);
|
| 526 |
+
if (!ks.length) h += '<div class="hint">Os jogadores estão escolhendo as cartas em segredo… (região destacada no mapa)</div>';
|
| 527 |
+
for (const e of ks) {
|
| 528 |
+
h += `<div class="who"><span class="dot" style="background:${gcol(+e)}"></span>J${e}<br>` + cc[e].map(c => cardHTML(c, 'rev')).join('') + '</div>';
|
| 529 |
+
}
|
| 530 |
+
setHTML('battle', h + '</div>');
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
// ---------- bandeja de decisão ----------
|
| 534 |
+
function selLabel(a) {
|
| 535 |
+
const D = S.decision;
|
| 536 |
+
if (D.phase === 'CHOOSE_ACTION') return ACT_PT[a.a][0];
|
| 537 |
+
if (D.phase === 'BATTLE_CARD') return CARD_PT[a.card][0];
|
| 538 |
+
if (D.phase === 'UNLOCK_PICK') return 'Desbloquear ' + POWER_PT[a.power][0];
|
| 539 |
+
return a.text;
|
| 540 |
+
}
|
| 541 |
+
function sel(idx) {
|
| 542 |
+
const a = S.decision.actions[idx];
|
| 543 |
+
SEL = {idx, a: a.a, card: a.card, power: a.power, label: selLabel(a)};
|
| 544 |
+
renderAll(true);
|
| 545 |
+
}
|
| 546 |
+
function cancelSel() { SEL = null; renderAll(true); }
|
| 547 |
+
function confirmSel() { if (SEL) act(SEL.a); }
|
| 548 |
+
function setHover(idx) { HOVER = idx < 0 ? null : S.decision.actions[idx]; renderBoard(); }
|
| 549 |
+
function actBid() { const v = +$('bidv').value; const a = S.decision.actions.find(x => x.bid === v); if (a) act(a.a); }
|
| 550 |
+
function actCamel() { act(S.decision.actions[+$('camelsel').value].a); }
|
| 551 |
+
function bar(statusCls, status, prompt, ctl) {
|
| 552 |
+
setHTML('tray', `<div class="decin"><div id="status" class="${statusCls}">${status}</div><div class="prompt">${prompt}</div><div class="ctl">${ctl || ''}</div></div>`);
|
| 553 |
+
}
|
| 554 |
+
function renderTray() {
|
| 555 |
+
const D = S.decision;
|
| 556 |
+
if (S.done) {
|
| 557 |
+
const w = S.winner;
|
| 558 |
+
bar('end', 'Fim de jogo', w === null ? 'Egito ateu (empate).' : `Vence J${w} (${GOD_PT[S.players[w].god]})${w === S.human ? ' — VOCÊ!' : ''}`,
|
| 559 |
+
'<button class="btn" onclick="openModal()">Nova partida</button>');
|
| 560 |
+
return;
|
| 561 |
+
}
|
| 562 |
+
if (!D) {
|
| 563 |
+
bar('', PLAY.on ? 'Oponentes jogando…' : 'Aguardando…', 'Use Pausar / Passo / Pular no topo para controlar a reprodução das jogadas.');
|
| 564 |
+
return;
|
| 565 |
+
}
|
| 566 |
+
const prompt = esc(PROMPT[D.phase] || D.phase);
|
| 567 |
+
const status = `Sua vez — J${S.human} (${GOD_PT[S.players[S.human].god]})`;
|
| 568 |
+
const btns = D.actions.map((a, idx) => ({a, idx})).filter(x => x.a.cell === undefined);
|
| 569 |
+
let ctl = '';
|
| 570 |
+
if (D.phase === 'BID') {
|
| 571 |
+
const mx = Math.max(...btns.map(x => x.a.bid));
|
| 572 |
+
ctl = `<input type="range" id="bidv" min="0" max="${mx}" value="0" oninput="document.getElementById('bidout').textContent=this.value"><span class="bidn" id="bidout">0</span> Seguidores <button class="btn" onclick="actBid()">Apostar</button>`;
|
| 573 |
+
} else if (D.phase === 'CAMEL_LINE') {
|
| 574 |
+
ctl = `<select id="camelsel" onchange="setHover(+this.value)">` + btns.map(x => `<option value="${x.idx}">${x.a.edges ? 'Linha ' + x.idx + ' (' + x.a.edges.length + ' camelos)' : 'Não colocar camelos'}</option>`).join('') + `</select><button class="btn" onclick="actCamel()">Confirmar</button>`;
|
| 575 |
+
} else if (['CHOOSE_ACTION', 'BATTLE_CARD', 'UNLOCK_PICK'].includes(D.phase)) {
|
| 576 |
+
ctl = SEL ? `<div class="conf"><b>${esc(SEL.label)}</b><button class="btn" onclick="confirmSel()">Confirmar</button><button class="btn dark" onclick="cancelSel()">Trocar</button></div>`
|
| 577 |
+
: '<span class="hint">Clique numa opção destacada em verde.</span>';
|
| 578 |
+
} else {
|
| 579 |
+
ctl = '<div class="acts">' + btns.map(x => {
|
| 580 |
+
const hv = (x.a.edges || x.a.region || x.a.regions) ? `onmouseenter="setHover(${x.idx})" onmouseleave="setHover(-1)"` : '';
|
| 581 |
+
return `<button class="btn dark" ${hv} onclick="act(${x.a.a})">${esc(cap(x.a.text.replace(/^escolhe a acao: /, '')))}</button>`;
|
| 582 |
+
}).join('') + '</div>';
|
| 583 |
+
if (!btns.length) ctl = '<span class="hint">As casas verdes no tabuleiro são as opções.</span>';
|
| 584 |
+
}
|
| 585 |
+
bar('me', status, prompt, ctl);
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
// ---------- registro, faixa e fim ----------
|
| 589 |
+
function renderLog() {
|
| 590 |
+
const el = $('log');
|
| 591 |
+
const stick = !el.scrollHeight || el.scrollTop + el.clientHeight >= el.scrollHeight - 30;
|
| 592 |
+
setHTML('log', LOG.slice(-120).map(l => {
|
| 593 |
+
const c = l.startsWith('>>>') ? 'ev1' : l.startsWith('FIM') ? 'fim' : l.startsWith('J' + S.human + ' ') ? 'me' : '';
|
| 594 |
+
return `<div class="${c}">${esc(l)}</div>`;
|
| 595 |
+
}).join(''));
|
| 596 |
+
if (stick) el.scrollTop = el.scrollHeight;
|
| 597 |
+
}
|
| 598 |
+
function renderBanner() {
|
| 599 |
+
const b = $('banner');
|
| 600 |
+
if (FRAME) {
|
| 601 |
+
const t = FRAME.lines[0].replace(/^J\d+ \([a-z]+\): /, '');
|
| 602 |
+
const who = FRAME.actor === S.human ? 'Você' : `J${FRAME.actor} · ${GOD_PT[S.players[FRAME.actor].god]}`;
|
| 603 |
+
b.style.display = 'block';
|
| 604 |
+
b.innerHTML = `<span class="dot" style="background:${gcol(FRAME.actor)}"></span><b>${esc(who)}</b> ${esc(t)}` + FRAME.lines.slice(1).map(x => `<div class="l2">${esc(x.trim())}</div>`).join('');
|
| 605 |
+
} else if (S.decision) {
|
| 606 |
+
b.style.display = 'block';
|
| 607 |
+
b.innerHTML = `<b>Sua vez</b> — ${esc(PROMPT[S.decision.phase] || '')}`;
|
| 608 |
+
} else b.style.display = 'none';
|
| 609 |
+
}
|
| 610 |
+
function renderEnd() {
|
| 611 |
+
if (S.done && ENDSHOWN !== S.seed + ':' + S.scenario && !PLAY.on) {
|
| 612 |
+
ENDSHOWN = S.seed + ':' + S.scenario;
|
| 613 |
+
const w = S.winner;
|
| 614 |
+
$('endt').textContent = w === null ? 'Egito ateu' : (w === S.human ? 'Vitória!' : 'Fim de jogo');
|
| 615 |
+
$('endp').textContent = w === null ? 'Todos os deuses foram esquecidos.' : `Vence J${w} (${GOD_PT[S.players[w].god]})${S.merged && S.merged[0] === w ? ` fundido com J${S.merged[1]}` : ''}.`;
|
| 616 |
+
$('endov').style.display = 'flex';
|
| 617 |
+
}
|
| 618 |
+
}
|
| 619 |
+
function renderAll(keep) {
|
| 620 |
+
if (!keep) { HOVER = null; SEL = null; }
|
| 621 |
+
setHTML('meta', `${S.scenario} · seed ${S.seed} · IA: ${esc(S.ai)}`);
|
| 622 |
+
setHTML('warn', (S.warnings || []).map(w => `<div class="warn">${esc(w)}</div>`).join(''));
|
| 623 |
+
renderOpps(); renderBoard(); renderDash(); renderDevo(); renderBattle(); renderGod(); renderHand(); renderTray(); renderLog(); renderBanner(); renderEnd();
|
| 624 |
+
}
|
| 625 |
+
|
| 626 |
+
// ---------- reprodução passo a passo ----------
|
| 627 |
+
function wait(ms) { return new Promise(res => { const t = setTimeout(done, ms); function done() { clearTimeout(t); PLAY.wake = null; res(); } PLAY.wake = done; }); }
|
| 628 |
+
function waitManual() { return new Promise(res => { PLAY.wake = () => { PLAY.wake = null; res(); }; }); }
|
| 629 |
+
async function playPayload(pl) {
|
| 630 |
+
const base = +$('speed').value;
|
| 631 |
+
PLAY.on = true; PLAY.skip = false;
|
| 632 |
+
$('bstep').disabled = !PLAY.paused;
|
| 633 |
+
if (base > 0) {
|
| 634 |
+
for (const fr of pl.frames) {
|
| 635 |
+
if (PLAY.skip) break;
|
| 636 |
+
S = Object.assign({}, fr.state, {decision: null});
|
| 637 |
+
FRAME = fr; LOG = LOG.concat(fr.lines);
|
| 638 |
+
renderAll();
|
| 639 |
+
if (PLAY.paused) await waitManual();
|
| 640 |
+
else await wait(Math.max(120, base * fr.slow * (fr.actor === fr.state.human ? 0.55 : 1)));
|
| 641 |
+
}
|
| 642 |
+
}
|
| 643 |
+
PLAY.on = false; FRAME = null;
|
| 644 |
+
S = pl.state; LOG = S.log || LOG;
|
| 645 |
+
renderAll();
|
| 646 |
+
}
|
| 647 |
+
async function act(a) {
|
| 648 |
+
if (busy || PLAY.on) return; busy = true;
|
| 649 |
+
try { SEL = null; HOVER = null; await playPayload(await api('/api/act', {a})); }
|
| 650 |
+
catch (e) { alert('Erro: ' + e.message); } finally { busy = false; }
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
// ---------- API, janela de nova partida ----------
|
| 654 |
+
async function api(path, body) {
|
| 655 |
+
const r = await fetch(path, body === undefined ? {} : {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)});
|
| 656 |
+
const j = await r.json();
|
| 657 |
+
if (!r.ok) throw new Error(j.erro || r.status);
|
| 658 |
+
return j;
|
| 659 |
+
}
|
| 660 |
+
function openModal() {
|
| 661 |
+
$('endov').style.display = 'none';
|
| 662 |
+
$('f_sc').innerHTML = Object.entries(OPT.scenarios).map(([n, p]) => `<option value="${n}">${n} (${p} jogadores)</option>`).join('');
|
| 663 |
+
$('f_god').innerHTML = '<option value="-1">Aleatório</option>' + OPT.gods.map((g, i) => `<option value="${i}">${GOD_PT[i]}</option>`).join('');
|
| 664 |
+
$('f_ai').innerHTML = '<option value="random">Aleatória</option>' + OPT.models.map((m, i) => `<option value="${i}">${esc(m)}</option>`).join('');
|
| 665 |
+
if (OPT.models.length) $('f_ai').value = '0';
|
| 666 |
+
$('f_sc').onchange = fillSeats; fillSeats();
|
| 667 |
+
$('modal').style.display = 'flex';
|
| 668 |
+
}
|
| 669 |
+
function fillSeats() {
|
| 670 |
+
const P = OPT.scenarios[$('f_sc').value];
|
| 671 |
+
let h = '<option value="-1">Aleatório</option>';
|
| 672 |
+
for (let s = 0; s < P; s++) h += `<option value="${s}">J${s}${s === 0 ? ' (joga primeiro)' : ''}</option>`;
|
| 673 |
+
$('f_seat').innerHTML = h;
|
| 674 |
+
}
|
| 675 |
+
async function startGame() {
|
| 676 |
+
PLAY.skip = true; if (PLAY.wake) PLAY.wake();
|
| 677 |
+
const body = {scenario: $('f_sc').value, human: +$('f_seat').value, god: +$('f_god').value, ai: $('f_ai').value, seed: $('f_seed').value};
|
| 678 |
+
$('modal').style.display = 'none';
|
| 679 |
+
try { LOG = []; ENDSHOWN = null; busy = true; await new Promise(r => setTimeout(r, 30)); await playPayload(await api('/api/new', body)); }
|
| 680 |
+
catch (e) { alert('Erro: ' + e.message); } finally { busy = false; }
|
| 681 |
+
}
|
| 682 |
+
async function init() {
|
| 683 |
+
B = await api('/api/board'); OPT = await api('/api/options');
|
| 684 |
+
$('btnnew').onclick = openModal; $('f_cancel').onclick = () => { $('modal').style.display = 'none'; };
|
| 685 |
+
$('f_go').onclick = startGame; $('coords').onchange = () => { if (S) renderBoard(); };
|
| 686 |
+
$('bpause').onclick = () => {
|
| 687 |
+
PLAY.paused = !PLAY.paused;
|
| 688 |
+
$('bpause').textContent = PLAY.paused ? '▶ Continuar' : '⏸ Pausar'; $('bstep').disabled = !PLAY.paused;
|
| 689 |
+
if (!PLAY.paused && PLAY.wake) PLAY.wake();
|
| 690 |
+
};
|
| 691 |
+
$('bstep').onclick = () => { if (PLAY.wake) PLAY.wake(); };
|
| 692 |
+
$('bskip').onclick = () => { PLAY.skip = true; PLAY.paused = false; $('bpause').textContent = '⏸ Pausar'; if (PLAY.wake) PLAY.wake(); };
|
| 693 |
+
const pl = await api('/api/state');
|
| 694 |
+
if (pl.state.started) { S = pl.state; LOG = S.log || []; renderAll(); } else openModal();
|
| 695 |
+
}
|
| 696 |
+
if (!window.__NOINIT) init();
|
| 697 |
+
</script>
|
| 698 |
+
</body>
|
| 699 |
+
</html>
|
jogar.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
jogar.py - Jogue Ankh contra as IAs no navegador.
|
| 3 |
+
|
| 4 |
+
python jogar.py --models ~/ankh_runs/run1/checkpoints/round_0040.zip
|
| 5 |
+
python jogar.py # sem --models: as IAs jogam aleatoriamente
|
| 6 |
+
|
| 7 |
+
Abre http://127.0.0.1:8765 . As regras sao as MESMAS do treino (ankh_game.py): este arquivo so
|
| 8 |
+
expoe o estado em JSON, aceita a sua jogada e deixa as IAs jogarem os outros assentos.
|
| 9 |
+
Precisa de jogar.html na mesma pasta. So os modelos exigem torch + sb3-contrib; o resto usa a
|
| 10 |
+
biblioteca padrao + numpy.
|
| 11 |
+
|
| 12 |
+
Cada jogada das IAs vira um QUADRO (frame) com o estado depois dela; a pagina os reproduz um a um.
|
| 13 |
+
|
| 14 |
+
Informacao secreta: as cartas escolhidas e os lances do Plague de outros jogadores NAO sao enviados
|
| 15 |
+
ao navegador (so as cartas ja reveladas e as ja usadas, que sao publicas no jogo).
|
| 16 |
+
"""
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import random
|
| 21 |
+
import threading
|
| 22 |
+
import time
|
| 23 |
+
import webbrowser
|
| 24 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
from ankh_game import (ACTION_END, ACTION_START, AnkhGame, CARD_BONUS, CARD_NAMES, EVENTS, GODS,
|
| 29 |
+
GUARDIAN_KINDS, KIND_NAMES, MON_TYPES, N_CHOICE, POWER_NAMES, RED_SPACES, TOP,
|
| 30 |
+
ANUBIS_SLOTS, Phase)
|
| 31 |
+
from ankh_map import SCENARIOS, build_board
|
| 32 |
+
from ankh_obs import Encoder
|
| 33 |
+
import replay
|
| 34 |
+
from replay import describe
|
| 35 |
+
|
| 36 |
+
replay.ACTIONS[3] = "Desbloquear poder Ankh" # o rotulo antigo do replay.py diz 'sem efeito'
|
| 37 |
+
|
| 38 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 39 |
+
SECRET_PHASES = (Phase.BATTLE_CARD, Phase.BID) # escolhas ocultas ate serem reveladas
|
| 40 |
+
# escolhas so de selecao (sem efeito visivel): nao geram quadro; o destino mostra a jogada inteira
|
| 41 |
+
SELECT_ONLY = (Phase.MOVE_SELECT, Phase.SUMMON_TYPE, Phase.ATTUNE_SRC, Phase.UNDERWORLD_SRC)
|
| 42 |
+
EVENT_TEXT = {"ctrl": "Controlar Monumento", "camel": "Caravana de Camelos", "conf": "CONFLITO"}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def seat_label(g, p):
|
| 46 |
+
return f"J{p} ({GODS[g.god[p]]})"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Session:
|
| 50 |
+
def __init__(self, models, device, deterministic):
|
| 51 |
+
self.lock = threading.RLock()
|
| 52 |
+
self.board = build_board()
|
| 53 |
+
self.models = [os.path.expanduser(m) for m in models]
|
| 54 |
+
self.device = device
|
| 55 |
+
self.deterministic = deterministic
|
| 56 |
+
self._policies = {}
|
| 57 |
+
self.g = None
|
| 58 |
+
self.human = 0
|
| 59 |
+
self.ai_kind = "random"
|
| 60 |
+
self.log = []
|
| 61 |
+
self.camel_new = None
|
| 62 |
+
self.warnings = []
|
| 63 |
+
self.frames = []
|
| 64 |
+
|
| 65 |
+
# ---------------- IA ----------------
|
| 66 |
+
def policy(self, idx):
|
| 67 |
+
if idx in self._policies:
|
| 68 |
+
return self._policies[idx]
|
| 69 |
+
try:
|
| 70 |
+
from sb3_contrib import MaskablePPO
|
| 71 |
+
m = MaskablePPO.load(self.models[idx], device=self.device)
|
| 72 |
+
det = self.deterministic
|
| 73 |
+
|
| 74 |
+
def act(obs, mask):
|
| 75 |
+
a, _ = m.predict(obs, action_masks=mask, deterministic=det)
|
| 76 |
+
return int(a)
|
| 77 |
+
except Exception as e: # noqa: BLE001
|
| 78 |
+
self.warnings.append(f"modelo {self.models[idx]} nao carregou ({e}); IA aleatoria")
|
| 79 |
+
print("AVISO:", self.warnings[-1])
|
| 80 |
+
act = None
|
| 81 |
+
self._policies[idx] = act
|
| 82 |
+
return act
|
| 83 |
+
|
| 84 |
+
def ai_action(self, dec):
|
| 85 |
+
mask = dec.mask
|
| 86 |
+
fn = None
|
| 87 |
+
if self.ai_kind != "random":
|
| 88 |
+
fn = self.policy(int(self.ai_kind))
|
| 89 |
+
if fn is None:
|
| 90 |
+
return int(random.choice(np.flatnonzero(mask)))
|
| 91 |
+
a = fn(self.enc.encode(dec), mask)
|
| 92 |
+
return a if mask[a] else int(random.choice(np.flatnonzero(mask)))
|
| 93 |
+
|
| 94 |
+
# ---------------- jogo ----------------
|
| 95 |
+
def new_game(self, scenario, human, god, ai, seed):
|
| 96 |
+
with self.lock:
|
| 97 |
+
seed = int(seed) if seed not in (None, "") else int(time.time()) % 10**6
|
| 98 |
+
self.g = AnkhGame(scenario, seed=seed, board=self.board)
|
| 99 |
+
P = SCENARIOS[scenario]["n_players"]
|
| 100 |
+
self.human = int(human) % P if human not in (None, "", -1) else int(np.random.default_rng(seed).integers(P))
|
| 101 |
+
rng = np.random.default_rng(seed + 1)
|
| 102 |
+
gods = [None] * P
|
| 103 |
+
if god not in (None, "", -1):
|
| 104 |
+
gods[self.human] = int(god)
|
| 105 |
+
for s in range(P):
|
| 106 |
+
if gods[s] is None:
|
| 107 |
+
free = [x for x in range(len(GODS)) if x not in gods]
|
| 108 |
+
gods[s] = int(rng.choice(free))
|
| 109 |
+
self.g.reset(seed=seed, gods=gods, scenario=scenario)
|
| 110 |
+
self.enc = Encoder(self.g)
|
| 111 |
+
self.ai_kind = "random" if ai in (None, "", "random") else str(int(ai))
|
| 112 |
+
self.log, self.camel_new, self.seed, self.frames = [], None, seed, []
|
| 113 |
+
self.say(f"Nova partida: {scenario} ({P} jogadores), seed {seed}. Voce e {seat_label(self.g, self.human)}.")
|
| 114 |
+
self._run_ai()
|
| 115 |
+
|
| 116 |
+
def say(self, text):
|
| 117 |
+
self.log.append(text)
|
| 118 |
+
del self.log[:-400]
|
| 119 |
+
|
| 120 |
+
def _before(self, dec):
|
| 121 |
+
g = self.g
|
| 122 |
+
if dec.phase == Phase.CAMEL_KEEP:
|
| 123 |
+
self.camel_new = sorted((r for r in g.regions if r not in g.tokens), key=min)
|
| 124 |
+
|
| 125 |
+
def _do(self, dec, a):
|
| 126 |
+
"""Executa uma jogada (de qualquer assento) e, se ela tem efeito visivel, grava um QUADRO."""
|
| 127 |
+
g = self.g
|
| 128 |
+
p = dec.player
|
| 129 |
+
self._before(dec)
|
| 130 |
+
ph = dec.phase
|
| 131 |
+
a = int(a)
|
| 132 |
+
skip = ph in SELECT_ONLY or a == g.A_DONE and ph in (Phase.MOVE_SELECT, Phase.ATTUNE_SRC, Phase.UNDERWORLD_SRC)
|
| 133 |
+
if ph == Phase.MOVE_DEST and a - g.A_CELL == dec.info.get("src"):
|
| 134 |
+
skip = True # a figura ficou onde estava
|
| 135 |
+
hl = {"from": None, "to": None, "line": None, "edges": None}
|
| 136 |
+
if g.A_CELL <= a < g.A_DONE:
|
| 137 |
+
c = a - g.A_CELL
|
| 138 |
+
if ph in (Phase.MOVE_DEST, Phase.PUSH_DEST, Phase.ATTUNE_DEST):
|
| 139 |
+
hl["from"], hl["to"] = dec.info.get("src"), c
|
| 140 |
+
else:
|
| 141 |
+
hl["to"] = c
|
| 142 |
+
if ph == Phase.CHOOSE_ACTION:
|
| 143 |
+
hl["line"] = a - g.A_TRACK
|
| 144 |
+
if ph == Phase.CAMEL_LINE and a > g.A_CAMEL:
|
| 145 |
+
hl["edges"] = [[g.ax2i[x] for x in tuple(e)] for e in dec.info["lines"][a - g.A_CAMEL - 1]]
|
| 146 |
+
if ph in SECRET_PHASES and p != self.human:
|
| 147 |
+
text = "escolhe uma carta (em segredo)" if ph == Phase.BATTLE_CARD else "faz um lance (em segredo)"
|
| 148 |
+
else:
|
| 149 |
+
try:
|
| 150 |
+
text = describe(g, dec, a)
|
| 151 |
+
except Exception: # noqa: BLE001
|
| 152 |
+
text = f"acao {a}"
|
| 153 |
+
dev0, alive0, ev0, cards0 = list(g.dev_pos), list(g.alive), g.event_idx, g.cur_cards
|
| 154 |
+
merged0 = g.merged
|
| 155 |
+
lines = [f"{seat_label(g, p)}: {text}"]
|
| 156 |
+
g.step(a)
|
| 157 |
+
if g.event_idx > ev0 and ev0 < len(EVENTS):
|
| 158 |
+
lines.append(f">>> EVENTO {ev0 + 1}/18: {EVENT_TEXT[EVENTS[ev0]]}")
|
| 159 |
+
if g.cur_cards is not None and g.cur_cards is not cards0 and g.cur_cards:
|
| 160 |
+
shown = ", ".join(f"{seat_label(g, e)}: {'+'.join(CARD_NAMES[c] for c in cs)}"
|
| 161 |
+
for e, cs in g.cur_cards.items() if cs)
|
| 162 |
+
if shown:
|
| 163 |
+
lines.append(f" cartas reveladas -> {shown}")
|
| 164 |
+
diff = [(q, g.dev_pos[q] - dev0[q]) for q in range(g.P) if g.dev_pos[q] != dev0[q]]
|
| 165 |
+
if diff and g.merged is merged0:
|
| 166 |
+
lines.append(" Devocao: " + ", ".join(f"J{q} {d:+d} (-> {g.dev_pos[q]})" for q, d in diff))
|
| 167 |
+
if g.merged is not merged0 and g.merged is not None:
|
| 168 |
+
lines.append(f" FUSAO: J{g.merged[1]} foi absorvido por J{g.merged[0]}")
|
| 169 |
+
for q in range(g.P):
|
| 170 |
+
if alive0[q] and not g.alive[q] and (g.merged is None or q not in g.merged or g.rep[q] == q):
|
| 171 |
+
if not (g.merged is not None and g.merged[1] == q):
|
| 172 |
+
lines.append(f" {seat_label(g, q)} foi ESQUECIDO")
|
| 173 |
+
if skip and len(lines) == 1:
|
| 174 |
+
return
|
| 175 |
+
if skip:
|
| 176 |
+
lines = lines[1:]
|
| 177 |
+
for ln in lines:
|
| 178 |
+
self.say(ln)
|
| 179 |
+
self.frames.append({"actor": p, "phase": ph.name, "lines": lines, "hl": hl,
|
| 180 |
+
"slow": 0.55 if ph in (Phase.MOVE_DEST, Phase.ATTUNE_DEST) else 1.0,
|
| 181 |
+
"state": self.state_json(light=True)})
|
| 182 |
+
|
| 183 |
+
def _run_ai(self):
|
| 184 |
+
g = self.g
|
| 185 |
+
guard = 0
|
| 186 |
+
while not g.done and g.decision.player != self.human:
|
| 187 |
+
dec = g.decision
|
| 188 |
+
self._do(dec, self.ai_action(dec))
|
| 189 |
+
guard += 1
|
| 190 |
+
if guard > 100000:
|
| 191 |
+
raise RuntimeError("loop das IAs")
|
| 192 |
+
if g.done:
|
| 193 |
+
self._announce_end()
|
| 194 |
+
|
| 195 |
+
def _announce_end(self):
|
| 196 |
+
g = self.g
|
| 197 |
+
if getattr(self, "_end_said", None) is g:
|
| 198 |
+
return
|
| 199 |
+
self._end_said = g
|
| 200 |
+
if g.winner is None:
|
| 201 |
+
self.say("FIM: Egito ateu (todos os deuses foram esquecidos).")
|
| 202 |
+
else:
|
| 203 |
+
self.say(f"FIM: vence {seat_label(g, g.winner)}.")
|
| 204 |
+
|
| 205 |
+
def act(self, a):
|
| 206 |
+
with self.lock:
|
| 207 |
+
g = self.g
|
| 208 |
+
if g is None or g.done or g.decision.player != self.human:
|
| 209 |
+
raise ValueError("nao e a sua vez")
|
| 210 |
+
dec = g.decision
|
| 211 |
+
if not (0 <= a < g.A_SIZE and dec.mask[a]):
|
| 212 |
+
raise ValueError("acao ilegal")
|
| 213 |
+
self.frames = []
|
| 214 |
+
self._do(dec, a)
|
| 215 |
+
self._run_ai()
|
| 216 |
+
|
| 217 |
+
def payload(self):
|
| 218 |
+
with self.lock:
|
| 219 |
+
out = {"frames": self.frames, "state": self.state_json()}
|
| 220 |
+
self.frames = []
|
| 221 |
+
return out
|
| 222 |
+
|
| 223 |
+
# ---------------- exportacao ----------------
|
| 224 |
+
def board_json(self):
|
| 225 |
+
b, g = self.board, AnkhGame("basic_2p", board=self.board)
|
| 226 |
+
cells = [{"i": i, "col": rc[0], "line": rc[1], "r2": b._pos[rc][0], "ter": g.terrain[i]}
|
| 227 |
+
for i, rc in enumerate(b.cells)]
|
| 228 |
+
river = []
|
| 229 |
+
for e in b.river_edges:
|
| 230 |
+
a, c = tuple(e)
|
| 231 |
+
if a in g.ax2i and c in g.ax2i:
|
| 232 |
+
river.append([g.ax2i[a], g.ax2i[c]])
|
| 233 |
+
return {"cells": cells, "river": river, "ncols": b.ncols,
|
| 234 |
+
"gods": GODS, "kinds": KIND_NAMES, "cards": CARD_NAMES, "card_bonus": CARD_BONUS,
|
| 235 |
+
"powers": POWER_NAMES, "events": EVENTS, "top": TOP, "red": RED_SPACES,
|
| 236 |
+
"action_start": ACTION_START, "action_end": ACTION_END}
|
| 237 |
+
|
| 238 |
+
def options(self):
|
| 239 |
+
return {"scenarios": {n: s["n_players"] for n, s in SCENARIOS.items()},
|
| 240 |
+
"gods": GODS, "models": [os.path.basename(m) for m in self.models],
|
| 241 |
+
"warnings": self.warnings}
|
| 242 |
+
|
| 243 |
+
def _anchor(self, region):
|
| 244 |
+
pos = [self.board._pos[self.board.cells[i]] for i in region]
|
| 245 |
+
cr = sum(p[0] for p in pos) / len(pos)
|
| 246 |
+
cc = sum(p[1] for p in pos) / len(pos)
|
| 247 |
+
land = [i for i in region if self.g.is_land[i]]
|
| 248 |
+
return min(land, key=lambda i: (self.board._pos[self.board.cells[i]][0] - cr) ** 2 * 0.5
|
| 249 |
+
+ (self.board._pos[self.board.cells[i]][1] - cc) ** 2 * 2)
|
| 250 |
+
|
| 251 |
+
def decision_json(self):
|
| 252 |
+
g = self.g
|
| 253 |
+
dec = g.decision
|
| 254 |
+
if g.done or dec is None or dec.player != self.human:
|
| 255 |
+
return None
|
| 256 |
+
acts = []
|
| 257 |
+
N = g.N
|
| 258 |
+
ops = None
|
| 259 |
+
if dec.phase == Phase.CAMEL_SWAP and self.camel_new:
|
| 260 |
+
new = self.camel_new
|
| 261 |
+
ops = [None]
|
| 262 |
+
for x in new:
|
| 263 |
+
for y in g.regions:
|
| 264 |
+
if y != x and not (y in new and new.index(y) < new.index(x)):
|
| 265 |
+
ops.append((x, y))
|
| 266 |
+
ops = ops[:N_CHOICE]
|
| 267 |
+
for a in np.flatnonzero(dec.mask):
|
| 268 |
+
a = int(a)
|
| 269 |
+
item = {"a": a}
|
| 270 |
+
try:
|
| 271 |
+
item["text"] = describe(g, dec, a)
|
| 272 |
+
except Exception: # noqa: BLE001
|
| 273 |
+
item["text"] = f"acao {a}"
|
| 274 |
+
if g.A_CELL <= a < g.A_DONE:
|
| 275 |
+
item["cell"] = a - g.A_CELL
|
| 276 |
+
elif dec.phase == Phase.BID:
|
| 277 |
+
item["bid"] = a - g.A_BID
|
| 278 |
+
elif dec.phase == Phase.BATTLE_CARD:
|
| 279 |
+
item["card"] = a - g.A_CARD
|
| 280 |
+
elif dec.phase == Phase.CAMEL_LINE and a > g.A_CAMEL:
|
| 281 |
+
line = dec.info["lines"][a - g.A_CAMEL - 1]
|
| 282 |
+
item["edges"] = [[g.ax2i[x] for x in tuple(e)] for e in line]
|
| 283 |
+
elif dec.phase == Phase.CAMEL_KEEP and self.camel_new:
|
| 284 |
+
item["region"] = sorted(self.camel_new[a - g.A_CHOICE])
|
| 285 |
+
item["text"] = f"a regiao em destaque mantem o token de ordem antigo ({'A' if a == g.A_CHOICE else 'B'})"
|
| 286 |
+
elif dec.phase == Phase.CAMEL_SWAP and ops:
|
| 287 |
+
op = ops[a - g.A_CHOICE]
|
| 288 |
+
if op is None:
|
| 289 |
+
item["text"] = "nao trocar tokens de ordem"
|
| 290 |
+
else:
|
| 291 |
+
x, y = op
|
| 292 |
+
item["regions"] = [sorted(x), sorted(y)]
|
| 293 |
+
item["text"] = f"trocar token {g.tokens[x]} (regiao A) com token {g.tokens[y]} (regiao B)"
|
| 294 |
+
elif dec.phase == Phase.UNLOCK_PICK:
|
| 295 |
+
item["power"] = a - g.A_POWER
|
| 296 |
+
acts.append(item)
|
| 297 |
+
out = {"phase": dec.phase.name, "actions": acts, "src": dec.info.get("src"),
|
| 298 |
+
"level": dec.info.get("level")}
|
| 299 |
+
return out
|
| 300 |
+
|
| 301 |
+
def state_json(self, light=False):
|
| 302 |
+
with self.lock:
|
| 303 |
+
g = self.g
|
| 304 |
+
if g is None:
|
| 305 |
+
return {"started": False}
|
| 306 |
+
N = g.N
|
| 307 |
+
cells = {}
|
| 308 |
+
for i in range(N):
|
| 309 |
+
c = {}
|
| 310 |
+
if g.fig_owner[i] >= 0:
|
| 311 |
+
c["f"] = [g.fig_owner[i], g.fig_kind[i], int(g.fig_sun[i])]
|
| 312 |
+
if g.claw[i] is not None:
|
| 313 |
+
d = g.claw[i]
|
| 314 |
+
c["cl"] = [j for j in (g.cyc_nb[i][d], g.cyc_nb[i][(d + 1) % 6]) if j >= 0]
|
| 315 |
+
if g.mon_type[i] is not None:
|
| 316 |
+
c["m"] = [MON_TYPES.index(g.mon_type[i]), g.mon_owner[i]]
|
| 317 |
+
if g.underworld[i]:
|
| 318 |
+
c["u"] = 1
|
| 319 |
+
if c:
|
| 320 |
+
cells[str(i)] = c
|
| 321 |
+
camels = [[g.ax2i[x] for x in tuple(e)] for e in g.camel_edges]
|
| 322 |
+
tokens = [[self._anchor(r), t] for r, t in g.tokens.items()]
|
| 323 |
+
players = []
|
| 324 |
+
for p in range(g.P):
|
| 325 |
+
e = g.rep[p]
|
| 326 |
+
players.append({
|
| 327 |
+
"seat": p, "god": g.god[p], "god2": g.god2[e], "ent": e, "alive": bool(g.alive[e]),
|
| 328 |
+
"absorbed": e != p, "superior": bool(g.merged is not None and g.merged[0] == p),
|
| 329 |
+
"dev": g.dev_pos[e], "followers": g.followers[e], "pool": g.warriors_pool[e],
|
| 330 |
+
"board_w": g.board_warriors(e), "ankh": g.ankh_pool[e],
|
| 331 |
+
"powers": sorted(g.powers[e]), "unlock_next": g.unlock_next[e],
|
| 332 |
+
"hand_n": len(g.hand[e]), "used": list(g.used[e]), "gpool": list(g.gpool[e]),
|
| 333 |
+
"sun_left": g.sun_left[e], "uw_off": g.uw_off[e],
|
| 334 |
+
"trapped": len(g.trapped[e]), "amun_declared": bool(g.amun_declared.get(e, False)),
|
| 335 |
+
"dev_order": g.dev_key(e)[1] if g.alive[e] else -1,
|
| 336 |
+
})
|
| 337 |
+
cur_cards = None
|
| 338 |
+
if g.cur_cards:
|
| 339 |
+
cur_cards = {str(e): list(cs) for e, cs in g.cur_cards.items()}
|
| 340 |
+
hand = sorted(g.hand[g.rep[self.human]])
|
| 341 |
+
s = {
|
| 342 |
+
"started": True, "scenario": g.scenario, "P": g.P, "human": self.human, "seed": self.seed,
|
| 343 |
+
"cells": cells, "camels": camels, "tokens": tokens, "players": players, "hand": hand,
|
| 344 |
+
"markers": list(g.markers), "event_idx": g.event_idx, "conflicts_done": g.conflicts_done,
|
| 345 |
+
"cur": g.cur, "merged": list(g.merged) if g.merged is not None else None,
|
| 346 |
+
"tiebreak_holder": g.tiebreak_holder, "tiebreak_available": bool(g.tiebreak_available),
|
| 347 |
+
"supply": g.supply, "camel_supply": g.camel_supply,
|
| 348 |
+
"g_card": {str(k): v for k, v in g.g_card.items()},
|
| 349 |
+
"g_supply": {str(k): v for k, v in g.g_supply.items()},
|
| 350 |
+
"cur_region": sorted(g.cur_region) if g.cur_region is not None else None,
|
| 351 |
+
"cur_cards": cur_cards,
|
| 352 |
+
"done": bool(g.done), "winner": g.winner,
|
| 353 |
+
"decision": None if light else self.decision_json(), "warnings": self.warnings,
|
| 354 |
+
"ai": "aleatoria" if self.ai_kind == "random" else os.path.basename(self.models[int(self.ai_kind)]),
|
| 355 |
+
"anubis_slots": ANUBIS_SLOTS,
|
| 356 |
+
}
|
| 357 |
+
if not light:
|
| 358 |
+
s["log"] = self.log[-150:]
|
| 359 |
+
if g.done:
|
| 360 |
+
s["end_reason"] = g.stats.get("end_reason")
|
| 361 |
+
return s
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class Handler(BaseHTTPRequestHandler):
|
| 365 |
+
session = None
|
| 366 |
+
|
| 367 |
+
def log_message(self, *a): # silencia o log por requisicao
|
| 368 |
+
pass
|
| 369 |
+
|
| 370 |
+
def _send(self, code, body, ctype="application/json"):
|
| 371 |
+
data = body if isinstance(body, bytes) else json.dumps(body).encode()
|
| 372 |
+
self.send_response(code)
|
| 373 |
+
self.send_header("Content-Type", ctype + "; charset=utf-8")
|
| 374 |
+
self.send_header("Content-Length", str(len(data)))
|
| 375 |
+
self.send_header("Cache-Control", "no-store")
|
| 376 |
+
self.end_headers()
|
| 377 |
+
self.wfile.write(data)
|
| 378 |
+
|
| 379 |
+
def do_GET(self):
|
| 380 |
+
s = Handler.session
|
| 381 |
+
if self.path in ("/", "/index.html"):
|
| 382 |
+
with open(os.path.join(HERE, "jogar.html"), "rb") as f:
|
| 383 |
+
self._send(200, f.read(), "text/html")
|
| 384 |
+
elif self.path == "/api/board":
|
| 385 |
+
self._send(200, s.board_json())
|
| 386 |
+
elif self.path == "/api/options":
|
| 387 |
+
self._send(200, s.options())
|
| 388 |
+
elif self.path == "/api/state":
|
| 389 |
+
self._send(200, {"frames": [], "state": s.state_json()})
|
| 390 |
+
else:
|
| 391 |
+
self._send(404, {"erro": "nao encontrado"})
|
| 392 |
+
|
| 393 |
+
def do_POST(self):
|
| 394 |
+
s = Handler.session
|
| 395 |
+
n = int(self.headers.get("Content-Length") or 0)
|
| 396 |
+
try:
|
| 397 |
+
body = json.loads(self.rfile.read(n) or b"{}")
|
| 398 |
+
if self.path == "/api/new":
|
| 399 |
+
s.new_game(body.get("scenario", "basic_2p"), body.get("human"), body.get("god"),
|
| 400 |
+
body.get("ai"), body.get("seed"))
|
| 401 |
+
elif self.path == "/api/act":
|
| 402 |
+
s.act(int(body["a"]))
|
| 403 |
+
else:
|
| 404 |
+
return self._send(404, {"erro": "nao encontrado"})
|
| 405 |
+
self._send(200, s.payload())
|
| 406 |
+
except Exception as e: # noqa: BLE001
|
| 407 |
+
self._send(400, {"erro": str(e)})
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def main():
|
| 411 |
+
ap = argparse.ArgumentParser()
|
| 412 |
+
ap.add_argument("--models", default="", help="checkpoints .zip separados por virgula (vazio = IA aleatoria)")
|
| 413 |
+
ap.add_argument("--port", type=int, default=8765)
|
| 414 |
+
ap.add_argument("--device", default="cpu")
|
| 415 |
+
ap.add_argument("--deterministic", action="store_true", help="a IA escolhe sempre a acao mais provavel")
|
| 416 |
+
ap.add_argument("--no-browser", action="store_true")
|
| 417 |
+
a = ap.parse_args()
|
| 418 |
+
models = [m for m in a.models.split(",") if m]
|
| 419 |
+
for m in models:
|
| 420 |
+
if not os.path.exists(os.path.expanduser(m)):
|
| 421 |
+
print("AVISO: arquivo nao encontrado:", m)
|
| 422 |
+
Handler.session = Session(models, a.device, a.deterministic)
|
| 423 |
+
srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
|
| 424 |
+
url = f"http://127.0.0.1:{a.port}"
|
| 425 |
+
print("Ankh rodando em", url, "(Ctrl+C para sair)")
|
| 426 |
+
if not a.no_browser:
|
| 427 |
+
threading.Timer(0.8, lambda: webbrowser.open(url)).start()
|
| 428 |
+
try:
|
| 429 |
+
srv.serve_forever()
|
| 430 |
+
except KeyboardInterrupt:
|
| 431 |
+
pass
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
if __name__ == "__main__":
|
| 435 |
+
main()
|
replay.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
replay.py - Joga partidas e imprime em TEXTO cada decisao e cada mudanca de estado,
|
| 3 |
+
para conferir as regras a olho (e achar bugs no jogo antes de o agente explora-los).
|
| 4 |
+
|
| 5 |
+
python replay.py # 1 partida, os dois jogadores aleatorios
|
| 6 |
+
python replay.py --seed 7 --maps # com o mapa depois de cada Conflito
|
| 7 |
+
python replay.py --scenario basic_4p --seed 7
|
| 8 |
+
python replay.py --models run1/checkpoints/round_0003.zip,run1/snapshots/snap_0002.zip
|
| 9 |
+
|
| 10 |
+
Mostra TUDO, inclusive as cartas e os lances secretos (e ferramenta de depuracao).
|
| 11 |
+
Sem --model0/--model1 o jogador correspondente joga aleatoriamente.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
from types import SimpleNamespace
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
from ankh_game import (AnkhGame, CARD_NAMES, EVENTS, GODS, KIND_NAMES, MON_TYPES, POWER_NAMES, Phase,
|
| 19 |
+
RED_SPACES)
|
| 20 |
+
from ankh_map import render
|
| 21 |
+
from ankh_obs import Encoder
|
| 22 |
+
|
| 23 |
+
ACTIONS = ["Mover figuras", "Invocar guerreiro", "Ganhar seguidores", "Desbloquear poder (sem efeito nesta versao)"]
|
| 24 |
+
EVENT_NAMES = {"ctrl": "Controlar Monumento", "camel": "Caravana de Camelos", "conf": "CONFLITO"}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def cell(g, i):
|
| 28 |
+
return "(%d,%d)" % g.board.cells[i]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def describe(g, dec, a):
|
| 32 |
+
ph = dec.phase
|
| 33 |
+
if ph == Phase.CHOOSE_ACTION:
|
| 34 |
+
return "escolhe a acao: " + ACTIONS[a - g.A_TRACK]
|
| 35 |
+
if ph == Phase.MOVE_SELECT:
|
| 36 |
+
return "termina o movimento" if a == g.A_DONE else f"seleciona a figura em {cell(g, a - g.A_CELL)}"
|
| 37 |
+
if ph == Phase.MOVE_DEST:
|
| 38 |
+
d, s = a - g.A_CELL, dec.info["src"]
|
| 39 |
+
return f"fica em {cell(g, s)}" if d == s else f"move {cell(g, s)} -> {cell(g, d)}"
|
| 40 |
+
if ph == Phase.SUMMON_TYPE:
|
| 41 |
+
if a == g.A_DONE:
|
| 42 |
+
return "nao faz a invocacao extra"
|
| 43 |
+
t = a - g.A_FIG
|
| 44 |
+
return "invoca: " + ("guerreiro" if t == 0 else "guerreiro preso por Anubis" if t == 1 else KIND_NAMES[t + 1])
|
| 45 |
+
if ph == Phase.SUMMON_DEST:
|
| 46 |
+
t = dec.info.get("fig", 0)
|
| 47 |
+
nome = "guerreiro" if t <= 1 else KIND_NAMES[t + 1]
|
| 48 |
+
return f"invoca {nome} em {cell(g, a - g.A_CELL)}" + (f" (extra: {dec.info['mode']})" if dec.info.get("mode") not in (None, "regular") else "")
|
| 49 |
+
if ph == Phase.UNLOCK_PICK:
|
| 50 |
+
return f"desbloqueia o poder {POWER_NAMES[a - g.A_POWER]} (nivel {dec.info['level']})"
|
| 51 |
+
if ph == Phase.AMUN_DECLARE:
|
| 52 |
+
return "ANUNCIA 2 cartas (Mysterious Forms)" if a == g.A_YESNO + 1 else "nao anuncia 2 cartas"
|
| 53 |
+
if ph == Phase.CLAW_POINT:
|
| 54 |
+
return f"aponta as garras do Scorpion em {cell(g, dec.info['src'])} (orientacao {a - g.A_CHOICE})"
|
| 55 |
+
if ph == Phase.PUSH_DEST:
|
| 56 |
+
return f"Satet empurra o inimigo de {cell(g, dec.info['src'])} para {cell(g, a - g.A_CELL)}"
|
| 57 |
+
if ph == Phase.UNDERWORLD_SRC:
|
| 58 |
+
return "nao realoca o Underworld" if a == g.A_DONE else f"realoca o token Underworld de {cell(g, a - g.A_CELL)}"
|
| 59 |
+
if ph == Phase.UNDERWORLD_DEST:
|
| 60 |
+
return "nao coloca Underworld" if a == g.A_DONE else f"Underworld em {cell(g, a - g.A_CELL)}"
|
| 61 |
+
if ph == Phase.ATTUNE_SRC:
|
| 62 |
+
return "termina Obelisk Attuned" if a == g.A_DONE else f"Obelisk Attuned: pega a figura em {cell(g, a - g.A_CELL)}"
|
| 63 |
+
if ph == Phase.ATTUNE_DEST:
|
| 64 |
+
return f"Obelisk Attuned: leva para {cell(g, a - g.A_CELL)}"
|
| 65 |
+
if ph == Phase.WORSHIP:
|
| 66 |
+
return "SACRIFICA 2 seguidores (Worshipful)" if a == g.A_YESNO + 1 else "nao usa Worshipful"
|
| 67 |
+
if ph == Phase.CONTROL_PICK:
|
| 68 |
+
m = a - g.A_CELL
|
| 69 |
+
return f"passa a controlar o {g.mon_type[m]} em {cell(g, m)}"
|
| 70 |
+
if ph == Phase.CAMEL_LINE:
|
| 71 |
+
k = a - g.A_CAMEL - 1
|
| 72 |
+
if k < 0:
|
| 73 |
+
return "nao coloca camelos"
|
| 74 |
+
edges = ["%s|%s" % tuple(cell(g, g.ax2i[x]) for x in sorted(e)) for e in dec.info["lines"][k]]
|
| 75 |
+
return f"coloca {len(edges)} camelos entre: " + " ".join(edges)
|
| 76 |
+
if ph == Phase.CAMEL_KEEP:
|
| 77 |
+
return f"a regiao {a - g.A_CHOICE} mantem o token antigo"
|
| 78 |
+
if ph == Phase.CAMEL_SWAP:
|
| 79 |
+
return "nao troca tokens" if a == g.A_CHOICE else f"troca de tokens (opcao {a - g.A_CHOICE})"
|
| 80 |
+
if ph == Phase.BATTLE_CARD:
|
| 81 |
+
return f"escolhe a carta {CARD_NAMES[a - g.A_CARD]}"
|
| 82 |
+
if ph == Phase.BUILD_TYPE:
|
| 83 |
+
t = a - g.A_BTYPE - 1
|
| 84 |
+
return "nao constroi" if t < 0 else f"constroi um {MON_TYPES[t]}"
|
| 85 |
+
if ph == Phase.BUILD_CELL:
|
| 86 |
+
return f"constroi em {cell(g, a - g.A_CELL)}"
|
| 87 |
+
if ph == Phase.BID:
|
| 88 |
+
return f"da um lance de {a - g.A_BID} seguidores"
|
| 89 |
+
if ph == Phase.TIEBREAK:
|
| 90 |
+
return "USA o token de desempate" if a == g.A_YESNO + 1 else "nao usa o token de desempate"
|
| 91 |
+
return f"acao {a}"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def snapshot(g):
|
| 95 |
+
mons = sorted((cell(g, i), g.mon_type[i], g.mon_owner[i]) for i in range(g.N) if g.mon_type[i])
|
| 96 |
+
return {
|
| 97 |
+
"devocao": list(g.dev_pos), "seguidores": list(g.followers),
|
| 98 |
+
"guerreiros no tabuleiro": [6 - w for w in g.warriors_pool],
|
| 99 |
+
"marcadores de acao": list(g.markers), "cartas usadas": [list(map(lambda c: CARD_NAMES[c], u)) for u in g.used],
|
| 100 |
+
"camelos no tabuleiro": len(g.camel_edges), "monumentos": mons, "vivos": list(g.alive),
|
| 101 |
+
"tokens de ordem": sorted(g.tokens.values()),
|
| 102 |
+
"poderes": [sorted(POWER_NAMES[w] for w in g.powers[p]) for p in range(g.P)],
|
| 103 |
+
"guardioes no pool": [[KIND_NAMES[k] for k in gp] for gp in g.gpool],
|
| 104 |
+
"guardioes em campo": sorted((p, KIND_NAMES[g.fig_kind[i]], cell(g, i)) for i in range(g.N)
|
| 105 |
+
for p in [g.fig_owner[i]] if p >= 0 and g.fig_kind[i] > 2),
|
| 106 |
+
"presos por Anubis": [list(t) for t in g.trapped],
|
| 107 |
+
"Radiant": sorted(cell(g, i) for i in range(g.N) if g.fig_sun[i]),
|
| 108 |
+
"Underworld": sorted(cell(g, i) for i in range(g.N) if g.underworld[i]),
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def show_map(g):
|
| 113 |
+
mons = [(g.mon_type[i], g.board.cells[i], None if g.mon_owner[i] < 0 else g.mon_owner[i])
|
| 114 |
+
for i in range(g.N) if g.mon_type[i]]
|
| 115 |
+
figs = {p: [("god" if g.fig_kind[i] == 1 else "warrior", g.board.cells[i]) # guardioes aparecem como 'w'
|
| 116 |
+
for i in range(g.N) if g.fig_owner[i] == p] for p in range(g.P)}
|
| 117 |
+
setup = SimpleNamespace(monuments=mons, figures=figs, region_of={})
|
| 118 |
+
print(render(g.board, setup))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def load_policy(path, device):
|
| 122 |
+
from sb3_contrib import MaskablePPO
|
| 123 |
+
m = MaskablePPO.load(path, device=device)
|
| 124 |
+
def act(obs, mask):
|
| 125 |
+
a, _ = m.predict(obs, action_masks=mask, deterministic=False)
|
| 126 |
+
return int(a)
|
| 127 |
+
return act
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def play(seed, policies, maps, scenario="basic_2p"):
|
| 131 |
+
g = AnkhGame(scenario, seed=seed)
|
| 132 |
+
enc, rng = Encoder(g), np.random.default_rng(seed)
|
| 133 |
+
dec = g.reset(seed=seed)
|
| 134 |
+
policies = (list(policies) + [None] * g.P)[:g.P] # assentos sem modelo jogam aleatoriamente
|
| 135 |
+
seats = ", ".join(f"J{p} ({GODS[g.god[p]]}): {'modelo' if policies[p] else 'aleatorio'}" for p in range(g.P))
|
| 136 |
+
print(f"===== partida seed={seed} | cenario {g.scenario} ({g.P} jogadores) | {seats} =====")
|
| 137 |
+
print(f" guardioes: nivel 1 = {KIND_NAMES[g.g_card[1]]}, nivel 2 = {KIND_NAMES[g.g_card[2]]}, nivel 3 = {KIND_NAMES[g.g_card[3]]}")
|
| 138 |
+
if maps:
|
| 139 |
+
show_map(g)
|
| 140 |
+
prev, n = snapshot(g), 0
|
| 141 |
+
while dec is not None:
|
| 142 |
+
p = dec.player
|
| 143 |
+
fn = policies[p]
|
| 144 |
+
a = fn(enc.encode(dec), dec.mask) if fn else int(rng.choice(np.flatnonzero(dec.mask)))
|
| 145 |
+
n += 1
|
| 146 |
+
text = describe(g, dec, a)
|
| 147 |
+
ev_before, conf_before = g.event_idx, g.conflicts_done
|
| 148 |
+
print(f"[{n:3d}] J{p} {dec.phase.name:<13} {text}")
|
| 149 |
+
dec = g.step(a)
|
| 150 |
+
if g.event_idx > ev_before:
|
| 151 |
+
print(f" >>> EVENTO {g.event_idx}/18: {EVENT_NAMES[EVENTS[g.event_idx - 1]]}")
|
| 152 |
+
cur = snapshot(g)
|
| 153 |
+
for k in cur:
|
| 154 |
+
if cur[k] != prev[k]:
|
| 155 |
+
print(f" · {k}: {prev[k]} -> {cur[k]}")
|
| 156 |
+
prev = cur
|
| 157 |
+
if maps and g.conflicts_done > conf_before:
|
| 158 |
+
show_map(g)
|
| 159 |
+
res = "empate (Egito ateu)" if g.winner is None else f"vence o deus do jogador {g.winner}" + (
|
| 160 |
+
f" (fundido com o jogador {g.merged[1]})" if g.merged and g.merged[0] == g.winner else "")
|
| 161 |
+
print(f"----- fim: {res} | devocao {g.dev_pos} (vermelho: < {RED_SPACES}) | {n} decisoes -----")
|
| 162 |
+
if maps:
|
| 163 |
+
show_map(g)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def main():
|
| 167 |
+
ap = argparse.ArgumentParser()
|
| 168 |
+
ap.add_argument("--games", type=int, default=1)
|
| 169 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 170 |
+
ap.add_argument("--scenario", default="basic_2p", help="basic_2p, basic_3p, basic_4p ou basic_5p")
|
| 171 |
+
ap.add_argument("--models", default="", help="checkpoints por assento, separados por virgula (vazio = aleatorio)")
|
| 172 |
+
ap.add_argument("--device", default="cpu")
|
| 173 |
+
ap.add_argument("--maps", action="store_true", help="imprime o mapa no inicio, apos cada Conflito e no fim")
|
| 174 |
+
a = ap.parse_args()
|
| 175 |
+
pol = [load_policy(m, a.device) if m else None for m in (a.models.split(",") if a.models else [])]
|
| 176 |
+
for i in range(a.games):
|
| 177 |
+
play(a.seed + i, pol, a.maps, a.scenario)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
main()
|
report.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regenera relatorio.md (e curvas.png) de uma run: python report.py --dir ~/ankh_runs/run1"""
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from ankh_report import render_markdown
|
| 6 |
+
|
| 7 |
+
if __name__ == "__main__":
|
| 8 |
+
ap = argparse.ArgumentParser()
|
| 9 |
+
ap.add_argument("--dir", required=True)
|
| 10 |
+
ap.add_argument("--no-plot", action="store_true")
|
| 11 |
+
a = ap.parse_args()
|
| 12 |
+
d = os.path.expanduser(a.dir)
|
| 13 |
+
text = render_markdown(d, plot=not a.no_plot)
|
| 14 |
+
print(text if text else f"nenhum report.jsonl em {d}")
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy
|
| 2 |
+
gymnasium
|
| 3 |
+
stable-baselines3
|
| 4 |
+
sb3-contrib
|
| 5 |
+
psutil
|
| 6 |
+
# PyTorch com CUDA: instale pelo comando de https://pytorch.org/get-started/locally/
|
round_0040.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a77688bae2535cbec4416a7f47983db1a98fdf8932fe4c9a27758bd31d4d9d6d
|
| 3 |
+
size 94766763
|
train_local.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
train_local.py - Treino PPO do Ankh no PC (CPU em varios processos + GPU em lote).
|
| 3 |
+
|
| 4 |
+
Instalar: pip install gymnasium stable-baselines3 sb3-contrib psutil
|
| 5 |
+
(e o PyTorch com CUDA: https://pytorch.org/get-started/locally/)
|
| 6 |
+
Rodar: python train_local.py --dir ~/ankh_runs/run1
|
| 7 |
+
Retomar: rode o mesmo comando (usa o ultimo checkpoint de --dir).
|
| 8 |
+
Fase 2 (soma zero):
|
| 9 |
+
python train_local.py --dir ~/ankh_runs/fase2 --zero-sum \
|
| 10 |
+
--init-from ~/ankh_runs/run1/checkpoints/round_0040.zip
|
| 11 |
+
Parar: Ctrl+C (salva um checkpoint antes de sair).
|
| 12 |
+
|
| 13 |
+
Deixe os arquivos ankh_*.py na mesma pasta deste script. Os processos de CPU
|
| 14 |
+
usam 'spawn', por isso o bloco `if __name__ == "__main__"` no fim e obrigatorio.
|
| 15 |
+
|
| 16 |
+
Saidas em --dir: checkpoints/, snapshots/ (oponentes do self-play), tb/ e metrics.csv.
|
| 17 |
+
"""
|
| 18 |
+
import argparse
|
| 19 |
+
import csv
|
| 20 |
+
import gc
|
| 21 |
+
import glob
|
| 22 |
+
import os
|
| 23 |
+
import random
|
| 24 |
+
import shutil
|
| 25 |
+
import time
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
from sb3_contrib import MaskablePPO
|
| 30 |
+
from stable_baselines3.common.callbacks import BaseCallback
|
| 31 |
+
|
| 32 |
+
from ankh_eval import evaluate, evaluate_matrix
|
| 33 |
+
from ankh_report import Agg, log_round, make_stats_callback, render_markdown
|
| 34 |
+
from ankh_game import GODS, AnkhGame
|
| 35 |
+
from ankh_map import SCENARIOS
|
| 36 |
+
from ankh_vec import BatchedSelfPlayVecEnv, TorchOpponent
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def default_workers():
|
| 40 |
+
"""Nucleos fisicos - 1 (deixa um para o processo principal, que cuida da GPU)."""
|
| 41 |
+
n = 0
|
| 42 |
+
try:
|
| 43 |
+
import psutil
|
| 44 |
+
n = psutil.cpu_count(logical=False) or 0
|
| 45 |
+
except ImportError:
|
| 46 |
+
pass
|
| 47 |
+
if not n:
|
| 48 |
+
n = max((os.cpu_count() or 2) // 2, 1)
|
| 49 |
+
return max(n - 1, 1)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class DiskCheckpoint(BaseCallback):
|
| 53 |
+
"""Salva o modelo a cada `every` passos e apaga os mais antigos."""
|
| 54 |
+
def __init__(self, every, directory, keep=3):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.every, self.dir, self.keep, self.last = every, directory, keep, 0
|
| 57 |
+
|
| 58 |
+
def _on_training_start(self):
|
| 59 |
+
self.last = self.num_timesteps
|
| 60 |
+
|
| 61 |
+
def _on_step(self):
|
| 62 |
+
if self.num_timesteps - self.last >= self.every:
|
| 63 |
+
self.last = self.num_timesteps
|
| 64 |
+
self.model.save(f"{self.dir}/step_{self.num_timesteps:010d}.zip")
|
| 65 |
+
for old in sorted(glob.glob(f"{self.dir}/step_*.zip"))[:-self.keep]:
|
| 66 |
+
os.remove(old)
|
| 67 |
+
return True
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def newest(directory):
|
| 71 |
+
files = glob.glob(f"{directory}/*.zip")
|
| 72 |
+
return max(files, key=os.path.getmtime) if files else None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def single(opp):
|
| 76 |
+
"""Adapta um oponente em lote (TorchOpponent) para decisoes individuais."""
|
| 77 |
+
return lambda obs, mask: int(opp(obs[None], mask[None])[0])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def parse(argv=None):
|
| 81 |
+
p = argparse.ArgumentParser()
|
| 82 |
+
p.add_argument("--dir", default="ankh_run", help="pasta de saida (checkpoints, snapshots, tb, metrics)")
|
| 83 |
+
p.add_argument("--workers", type=int, default=0, help="processos de CPU (0 = nucleos fisicos - 1)")
|
| 84 |
+
p.add_argument("--envs", type=int, default=0, help="partidas em paralelo (0 = 16 por worker)")
|
| 85 |
+
p.add_argument("--round-steps", type=int, default=400_000)
|
| 86 |
+
p.add_argument("--total-rounds", type=int, default=40)
|
| 87 |
+
p.add_argument("--save-every", type=int, default=100_000)
|
| 88 |
+
p.add_argument("--keep-step-ckpts", type=int, default=3)
|
| 89 |
+
p.add_argument("--keep-rounds", type=int, default=10)
|
| 90 |
+
p.add_argument("--snapshot-every", type=int, default=1)
|
| 91 |
+
p.add_argument("--eval-per-god", type=int, default=8, help="partidas de avaliacao por deus E por cenario")
|
| 92 |
+
p.add_argument("--scenarios", default="all", help="cenarios usados (nomes separados por virgula) ou all")
|
| 93 |
+
p.add_argument("--players", default="2,3,4,5", help="numeros de jogadores treinados, ex.: 2 ou 2,3")
|
| 94 |
+
p.add_argument("--matrix-every", type=int, default=5, help="a cada N rounds, matriz de confrontos entre deuses (0 = nunca)")
|
| 95 |
+
p.add_argument("--matrix-games", type=int, default=3, help="partidas por par de deuses na matriz")
|
| 96 |
+
p.add_argument("--god-pool", default="0,1,2,3,4",
|
| 97 |
+
help="deuses sorteados (0 Amun, 1 Anubis, 2 Isis, 3 Osiris, 4 Ra), ex.: 4 ou 0,4")
|
| 98 |
+
p.add_argument("--n-steps", type=int, default=128)
|
| 99 |
+
p.add_argument("--lr", type=float, default=3e-4)
|
| 100 |
+
p.add_argument("--merged-reward", choices=["normal", "zero"], default="normal",
|
| 101 |
+
help="zero: os assentos de um deus fundido recebem recompensa 0 depois da fusao")
|
| 102 |
+
p.add_argument("--zero-sum", action="store_true",
|
| 103 |
+
help="recompensas de soma zero (pesos simetricos, Egito ateu = 0)")
|
| 104 |
+
p.add_argument("--init-from", default="",
|
| 105 |
+
help="checkpoint .zip de uma fase anterior: usa os pesos como ponto de partida "
|
| 106 |
+
"e o semeia como primeiro oponente do self-play")
|
| 107 |
+
return p.parse_args(argv)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def main(argv=None):
|
| 111 |
+
a = parse(argv)
|
| 112 |
+
root = os.path.abspath(os.path.expanduser(a.dir))
|
| 113 |
+
ckpt, snap, tb, metrics = (f"{root}/checkpoints", f"{root}/snapshots", f"{root}/tb", f"{root}/metrics.csv")
|
| 114 |
+
for d in (ckpt, snap, tb):
|
| 115 |
+
os.makedirs(d, exist_ok=True)
|
| 116 |
+
|
| 117 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 118 |
+
if device == "cpu":
|
| 119 |
+
print("AVISO: GPU nao encontrada; treinando na CPU (bem mais lento).")
|
| 120 |
+
workers = a.workers or default_workers()
|
| 121 |
+
n_envs = a.envs or 16 * workers
|
| 122 |
+
batch = max((a.n_steps * n_envs) // 4, 64)
|
| 123 |
+
print("saida em:", root, "| relatorio:", f"{root}/relatorio.md")
|
| 124 |
+
print(f"dispositivo: {device} | workers: {workers} | partidas: {n_envs} | lote de coleta: {a.n_steps * n_envs}")
|
| 125 |
+
|
| 126 |
+
god_pool = [int(x) for x in a.god_pool.split(",")]
|
| 127 |
+
print("deuses sorteados:", [GODS[x] for x in god_pool])
|
| 128 |
+
wanted = [int(x) for x in a.players.split(",")]
|
| 129 |
+
names = list(SCENARIOS) if a.scenarios == "all" else a.scenarios.split(",")
|
| 130 |
+
names = [n for n in names if SCENARIOS[n]["n_players"] in wanted]
|
| 131 |
+
probe = AnkhGame(names)
|
| 132 |
+
scenarios = list(probe.scenarios)
|
| 133 |
+
print("cenarios usados:", {n: SCENARIOS[n]["n_players"] for n in scenarios})
|
| 134 |
+
for n, errs in probe.skipped.items():
|
| 135 |
+
print(f"AVISO: cenario {n} ignorado (erro nos dados): {errs[0]}")
|
| 136 |
+
|
| 137 |
+
venv = BatchedSelfPlayVecEnv(n_envs=n_envs, n_workers=workers, seed=int(time.time()) % 100000,
|
| 138 |
+
zero_sum=a.zero_sum, god_pool=god_pool, scenarios=scenarios,
|
| 139 |
+
merged_reward=a.merged_reward)
|
| 140 |
+
print("recompensas:", "SOMA ZERO" if a.zero_sum else "padrao (nao simetricas)")
|
| 141 |
+
last = newest(ckpt)
|
| 142 |
+
if last:
|
| 143 |
+
model = MaskablePPO.load(last, env=venv, device=device, tensorboard_log=tb)
|
| 144 |
+
print("RETOMANDO de", os.path.basename(last), "| passos ja feitos:", model.num_timesteps)
|
| 145 |
+
else:
|
| 146 |
+
model = MaskablePPO("MlpPolicy", venv, n_steps=a.n_steps, batch_size=batch, n_epochs=4, gamma=0.995,
|
| 147 |
+
gae_lambda=0.95, ent_coef=0.01, learning_rate=a.lr, verbose=0, device=device,
|
| 148 |
+
tensorboard_log=tb, policy_kwargs=dict(net_arch=[512, 512]))
|
| 149 |
+
print("treino NOVO")
|
| 150 |
+
if a.init_from:
|
| 151 |
+
model.set_parameters(os.path.expanduser(a.init_from), device=device)
|
| 152 |
+
print("pesos iniciais carregados de", a.init_from)
|
| 153 |
+
if not glob.glob(f"{snap}/snap_*.zip"):
|
| 154 |
+
shutil.copy(os.path.expanduser(a.init_from), f"{snap}/snap_0000.zip")
|
| 155 |
+
|
| 156 |
+
if not os.path.exists(metrics):
|
| 157 |
+
with open(metrics, "w", newline="") as f:
|
| 158 |
+
csv.writer(f).writerow(["timesteps", "win_vs_prev", "atheist_vs_prev", "prev_snapshot",
|
| 159 |
+
"train_opponent", "steps_per_s", "minutes"]
|
| 160 |
+
+ [f"w_{g}" for g in GODS])
|
| 161 |
+
|
| 162 |
+
goal, t0, opp = a.total_rounds * a.round_steps, time.time(), None
|
| 163 |
+
try:
|
| 164 |
+
while model.num_timesteps < goal:
|
| 165 |
+
todo = a.round_steps - model.num_timesteps % a.round_steps
|
| 166 |
+
del opp
|
| 167 |
+
gc.collect()
|
| 168 |
+
if device == "cuda":
|
| 169 |
+
torch.cuda.empty_cache()
|
| 170 |
+
|
| 171 |
+
# Seleção do oponente de treino
|
| 172 |
+
pool = sorted(glob.glob(f"{snap}/snap_*.zip"))
|
| 173 |
+
if not pool:
|
| 174 |
+
opp, opp_name = None, "aleatorio"
|
| 175 |
+
elif len(pool) == 1:
|
| 176 |
+
path = pool[0]
|
| 177 |
+
opp, opp_name = TorchOpponent(path, device=device), os.path.basename(path)
|
| 178 |
+
else:
|
| 179 |
+
if random.random() < 0.5:
|
| 180 |
+
path = pool[-1] # 50% último modelo
|
| 181 |
+
else:
|
| 182 |
+
candidates = pool[:-1]
|
| 183 |
+
if len(candidates) <= 4:
|
| 184 |
+
path = random.choice(candidates)
|
| 185 |
+
else:
|
| 186 |
+
if random.random() < 0.8:
|
| 187 |
+
path = random.choice(candidates[-4:])
|
| 188 |
+
else:
|
| 189 |
+
path = random.choice(candidates[:-4])
|
| 190 |
+
opp, opp_name = TorchOpponent(path, device=device), os.path.basename(path)
|
| 191 |
+
|
| 192 |
+
venv.set_opponent(opp)
|
| 193 |
+
t_round = time.time()
|
| 194 |
+
agg_train = Agg()
|
| 195 |
+
model.learn(todo, reset_num_timesteps=False, tb_log_name="ppo", progress_bar=False,
|
| 196 |
+
callback=[DiskCheckpoint(a.save_every, ckpt, a.keep_step_ckpts), make_stats_callback(agg_train)])
|
| 197 |
+
sps = todo / (time.time() - t_round)
|
| 198 |
+
r = model.num_timesteps // a.round_steps
|
| 199 |
+
model.save(f"{ckpt}/round_{r:04d}.zip")
|
| 200 |
+
for old in sorted(glob.glob(f"{ckpt}/round_*.zip"))[:-a.keep_rounds]:
|
| 201 |
+
os.remove(old)
|
| 202 |
+
|
| 203 |
+
# Avaliação única contra o snapshot anterior
|
| 204 |
+
agg_p = Agg()
|
| 205 |
+
prev_files = sorted(glob.glob(f"{snap}/snap_*.zip")) # ANTES de salvar o novo snapshot
|
| 206 |
+
if prev_files:
|
| 207 |
+
prev_name = os.path.basename(prev_files[-1])
|
| 208 |
+
prev_fn = single(TorchOpponent(prev_files[-1], device=device))
|
| 209 |
+
pw, pa, by_god = evaluate(model, a.eval_per_god, prev_fn, god_pool=god_pool, agg=agg_p, scenarios=scenarios)
|
| 210 |
+
else:
|
| 211 |
+
prev_name, pw, pa, prev_fn, by_god = "", 0.0, 0.0, None, {}
|
| 212 |
+
|
| 213 |
+
if r % a.snapshot_every == 0:
|
| 214 |
+
model.save(f"{snap}/snap_{r:04d}.zip")
|
| 215 |
+
minutes = (time.time() - t0) / 60
|
| 216 |
+
matrix = None
|
| 217 |
+
if a.matrix_every and r % a.matrix_every == 0 and prev_fn:
|
| 218 |
+
matrix = evaluate_matrix(model, prev_fn, god_pool, a.matrix_games, scenarios=scenarios)
|
| 219 |
+
|
| 220 |
+
log_round(root, {"round": r, "steps": model.num_timesteps, "minutes": minutes, "opponent": opp_name,
|
| 221 |
+
"prev_snapshot": prev_name, "rewards": "soma zero" if a.zero_sum else "padrao",
|
| 222 |
+
"gods": [GODS[x] for x in god_pool], "scenarios": {n: SCENARIOS[n]["n_players"] for n in scenarios},
|
| 223 |
+
"train": agg_train.to_dict(),
|
| 224 |
+
"eval_prev": agg_p.to_dict() if prev_name else None,
|
| 225 |
+
"matrix": matrix, "matrix_vs": prev_name or "nenhum"})
|
| 226 |
+
render_markdown(root)
|
| 227 |
+
|
| 228 |
+
with open(metrics, "a", newline="") as f:
|
| 229 |
+
csv.writer(f).writerow([model.num_timesteps, pw, pa, prev_name, opp_name,
|
| 230 |
+
round(sps), round(minutes, 1)]
|
| 231 |
+
+ [round(by_god.get(g, float("nan")), 2) for g in range(len(GODS))])
|
| 232 |
+
|
| 233 |
+
vs_prev = f"vs {prev_name}: vitorias {pw:.0%}, Egito ateu {pa:.0%}" if prev_name else "vs anterior: (sem snapshot ainda)"
|
| 234 |
+
per_god = " ".join(f"{GODS[g][:3]} {w:.0%}" for g, w in by_god.items()) if by_god else ""
|
| 235 |
+
god_str = f" ({per_god})" if per_god else ""
|
| 236 |
+
print(f"round {r:3d} | passos {model.num_timesteps:>10,} | {sps:,.0f} passos/s | {vs_prev}{god_str} | treinou contra: {opp_name} | {minutes:.0f} min")
|
| 237 |
+
print("treino concluido")
|
| 238 |
+
except KeyboardInterrupt:
|
| 239 |
+
path = f"{ckpt}/step_{model.num_timesteps:010d}.zip"
|
| 240 |
+
model.save(path)
|
| 241 |
+
print("\ninterrompido; checkpoint salvo em", path)
|
| 242 |
+
finally:
|
| 243 |
+
venv.close()
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
main()
|