Web front-end
Browse files- README.md +91 -83
- jogar.bat +5 -0
- server.py +289 -0
- web/index.html +258 -0
README.md
CHANGED
|
@@ -1,83 +1,91 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: mit
|
| 3 |
-
tags:
|
| 4 |
-
- poker
|
| 5 |
-
- reinforcement-learning
|
| 6 |
-
- self-play
|
| 7 |
-
- texas-holdem
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
# Poker AI — No-Limit Texas Hold'em para 2 a 23 jogadores
|
| 11 |
-
|
| 12 |
-
Agente de No-Limit Hold'em treinado do zero por **self-play com reforço (PPO)**, inteiramente em GPU (NVIDIA B200 na Modal).
|
| 13 |
-
Uma única rede joga em **qualquer mesa de 2 até 23 jogadores** (heads-up, 6-max, full ring 9, 12, 15, 23...), com stacks diferentes por jogador e antes opcionais.
|
| 14 |
-
|
| 15 |
-
## Arquivos
|
| 16 |
-
|
| 17 |
-
| arquivo | conteúdo |
|
| 18 |
-
|---|---|
|
| 19 |
-
| `model.pt` | pesos mais recentes da política (rede ator) |
|
| 20 |
-
| `checkpoints/model_itXXXXX.pt` | snapshots a cada ~1h de treino |
|
| 21 |
-
| `training_state/ckpt.pt` | estado completo (ator + crítico + otimizador + liga) para continuar o treino |
|
| 22 |
-
| `metrics.jsonl` | métricas de treino e avaliações periódicas contra bots |
|
| 23 |
-
| `poker_core.py` | motor de NLHE vetorizado em PyTorch (regras completas, side pots, avaliador de mãos com lookup table) |
|
| 24 |
-
| `model.py` | rede Transformer |
|
| 25 |
-
| `train.py` | treino PPO self-play + liga de oponentes |
|
| 26 |
-
| `play.py` | jogar contra a IA no terminal / modo conselheiro para qualquer mesa |
|
| 27 |
-
|
| 28 |
-
##
|
| 29 |
-
|
| 30 |
-
```bash
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
```
|
| 49 |
-
|
| 50 |
-
#
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
-
|
| 62 |
-
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
tags:
|
| 4 |
+
- poker
|
| 5 |
+
- reinforcement-learning
|
| 6 |
+
- self-play
|
| 7 |
+
- texas-holdem
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# Poker AI — No-Limit Texas Hold'em para 2 a 23 jogadores
|
| 11 |
+
|
| 12 |
+
Agente de No-Limit Hold'em treinado do zero por **self-play com reforço (PPO)**, inteiramente em GPU (NVIDIA B200 na Modal).
|
| 13 |
+
Uma única rede joga em **qualquer mesa de 2 até 23 jogadores** (heads-up, 6-max, full ring 9, 12, 15, 23...), com stacks diferentes por jogador e antes opcionais.
|
| 14 |
+
|
| 15 |
+
## Arquivos
|
| 16 |
+
|
| 17 |
+
| arquivo | conteúdo |
|
| 18 |
+
|---|---|
|
| 19 |
+
| `model.pt` | pesos mais recentes da política (rede ator) |
|
| 20 |
+
| `checkpoints/model_itXXXXX.pt` | snapshots a cada ~1h de treino |
|
| 21 |
+
| `training_state/ckpt.pt` | estado completo (ator + crítico + otimizador + liga) para continuar o treino |
|
| 22 |
+
| `metrics.jsonl` | métricas de treino e avaliações periódicas contra bots |
|
| 23 |
+
| `poker_core.py` | motor de NLHE vetorizado em PyTorch (regras completas, side pots, avaliador de mãos com lookup table) |
|
| 24 |
+
| `model.py` | rede Transformer |
|
| 25 |
+
| `train.py` | treino PPO self-play + liga de oponentes |
|
| 26 |
+
| `play.py` | jogar contra a IA no terminal / modo conselheiro para qualquer mesa |
|
| 27 |
+
|
| 28 |
+
## Interface web (jogar / assistir)
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
python server.py # abre http://localhost:8765 no navegador
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Mesa visual para 2–23 jogadores: jogar contra a IA, ou assistir IA vs IA com as cartas abertas. Mostra o "cérebro da IA" (probabilidade de cada ação), dica da IA na sua vez, histórico e resultado em bb/100. Precisa de `server.py`, `web/index.html`, `play.py`, `model.py`, `poker_core.py`.
|
| 35 |
+
|
| 36 |
+
## Como usar (terminal / API)
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
pip install torch huggingface_hub
|
| 40 |
+
# baixe poker_core.py, model.py, play.py deste repositório
|
| 41 |
+
python play.py play --players 6 --stack 100 # você contra 5 IAs
|
| 42 |
+
python play.py play --players 2 # heads-up
|
| 43 |
+
python play.py advisor # a IA sugere jogadas numa mesa real (qualquer nº de jogadores)
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
API em Python:
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
from play import PokerAI, Advisor
|
| 50 |
+
adv = Advisor(PokerAI.load()) # baixa model.pt do Hugging Face
|
| 51 |
+
adv.new_hand(n=9, button=0, stacks=[100]*9, hero=4, hole="Ah Kd")
|
| 52 |
+
adv.act(3, "raise", 3) # assento 3 aumenta para 3bb (valor = aposta total na rodada)
|
| 53 |
+
print(adv.suggest()) # {'best': 'raise to 10.00 (...)', 'options': [...], ...}
|
| 54 |
+
adv.act(4, "raise", 10); adv.act(5, "fold") ...
|
| 55 |
+
adv.board("Ah 7c 2d") # quando sair o flop/turn/river
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
## Como funciona
|
| 59 |
+
|
| 60 |
+
- **Motor**: dezenas de milhares de mesas simuladas em paralelo na GPU, com regras completas de NLHE: blinds, antes, min-raise, all-in incompleto (não reabre a ação), side pots múltiplos e split pots.
|
| 61 |
+
- **Ações**: fold, check/call, min-raise, raise de 33%/50%/75%/100%/150%/250% do pote, all-in. Ações de oponentes de qualquer tamanho são aceitas (modo conselheiro).
|
| 62 |
+
- **Rede (ator)**: Transformer (d=256, 4 camadas) sobre tokens [estado global, 7 cartas, 1 token por assento]. Como os assentos são tokens, a mesma rede serve para qualquer número de jogadores. Recebe também equidade Monte Carlo (vs 1 mão aleatória e vs todos os oponentes vivos) e a categoria da mão feita.
|
| 63 |
+
- **Crítico privilegiado**: durante o treino a função valor vê as cartas de todos e o board completo (reduz muito a variância; não é usado para jogar).
|
| 64 |
+
- **Liga**: além de self-play puro, parte das mesas tem versões antigas da rede e bots heurísticos (calling station, TAG, rock, maniac, aleatório, equity-caller), para evitar estratégias que só funcionam contra si mesma.
|
| 65 |
+
- **Distribuição das mesas**: 2–9 jogadores (heads-up mais frequente) e 10–23 jogadores; stacks de 3 a 300 BB.
|
| 66 |
+
|
| 67 |
+
## Treino realizado
|
| 68 |
+
|
| 69 |
+
- 261 iterações PPO, **75,5 milhões de mãos** de self-play (≈600 milhões de decisões), 4,1 h numa NVIDIA B200.
|
| 70 |
+
- Estratégia final: ~40% fold, ~40% check/call, ~18% raises, ~2% all-in.
|
| 71 |
+
|
| 72 |
+
## Resultados finais (bb/100 da IA em 1 assento contra o resto da mesa, stacks 100bb, ± erro padrão)
|
| 73 |
+
|
| 74 |
+
| oponentes | heads-up | 6 jogadores | 9 jogadores | 15 jogadores |
|
| 75 |
+
|---|---|---|---|---|
|
| 76 |
+
| TAG (tight-aggressive por equidade) | +188 ± 18 | +112 ± 18 | +126 ± 19 | +87 ± 15 |
|
| 77 |
+
| Rock (super tight) | +117 ± 13 | +45 ± 12 | +40 ± 12 | — |
|
| 78 |
+
| Maniac (agressivo) | +476 ± 30 | +630 ± 81 | +859 ± 139 | +1100 ± 201 |
|
| 79 |
+
| Calling station | +1072 ± 32 | +4793 ± 149 | +5153 ± 243 | +6114 ± 345 |
|
| 80 |
+
| Aleatório | +340 ± 27 | +772 ± 64 | +776 ± 100 | — |
|
| 81 |
+
| Versão antiga dela mesma (iter. 20) | +187 ± 17 | +210 ± 28 | — | — |
|
| 82 |
+
|
| 83 |
+
No início do treino a IA perdia entre −900 e −1500 bb/100 para o bot TAG. Para comparação, um jogador profissional de cash game costuma ganhar entre +5 e +10 bb/100.
|
| 84 |
+
|
| 85 |
+
## Limitações (honestas)
|
| 86 |
+
|
| 87 |
+
**Não há garantia de que seja melhor que qualquer humano**: o orçamento total foi ~US$30 de GPU (≈4h de B200).
|
| 88 |
+
Bots sobre-humanos como Libratus e Pluribus usaram busca em tempo real e muito mais computação. Veja as avaliações em `metrics.jsonl`
|
| 89 |
+
(bb/100 contra cada bot, em mesas de 2, 6, 9 e 15 jogadores) para o nível real.
|
| 90 |
+
|
| 91 |
+
Uso educacional/pesquisa. Usar bots em sites de poker com dinheiro real normalmente viola os termos de uso desses sites.
|
jogar.bat
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
cd /d "%~dp0"
|
| 3 |
+
echo Iniciando Poker AI... (feche esta janela para desligar)
|
| 4 |
+
python server.py %*
|
| 5 |
+
pause
|
server.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Local web front-end for the poker AI.
|
| 3 |
+
|
| 4 |
+
python server.py # abre http://localhost:8765
|
| 5 |
+
python server.py --model ckpts/checkpoints/model_it00261.pt --port 8765
|
| 6 |
+
"""
|
| 7 |
+
import argparse
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import threading
|
| 11 |
+
import webbrowser
|
| 12 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
from play import PokerAI, card_str
|
| 17 |
+
from poker_core import ACTION_NAMES, N_ACTIONS, NREV, HandEvaluator, PokerEnv
|
| 18 |
+
|
| 19 |
+
torch.set_grad_enabled(False)
|
| 20 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 21 |
+
CAT_NAMES = ["Carta alta", "Par", "Dois pares", "Trinca", "Sequência", "Flush", "Full house", "Quadra",
|
| 22 |
+
"Straight flush"]
|
| 23 |
+
STREETS = ["Pré-flop", "Flop", "Turn", "River"]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def fmt(x):
|
| 27 |
+
x = round(float(x), 2)
|
| 28 |
+
return f"{x:g}"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Game:
|
| 32 |
+
def __init__(self, ai, ev):
|
| 33 |
+
self.ai, self.ev = ai, ev
|
| 34 |
+
self.lock = threading.Lock()
|
| 35 |
+
self.env = None
|
| 36 |
+
|
| 37 |
+
# ---------------------------------------------------------------- setup
|
| 38 |
+
def new_game(self, players=6, stack=100.0, mode="play", reveal=False):
|
| 39 |
+
players = max(2, min(23, int(players)))
|
| 40 |
+
self.n = players
|
| 41 |
+
self.stack0 = float(stack)
|
| 42 |
+
self.hero = 0 if mode == "play" else -1
|
| 43 |
+
self.reveal = bool(reveal) or self.hero < 0
|
| 44 |
+
self.env = PokerEnv(1, players, [0] * (players - 2) + [1], "cpu", self.ev, eq_samples=64, ante_prob=0.0)
|
| 45 |
+
self.profit = [0.0] * players
|
| 46 |
+
self.hands = 0
|
| 47 |
+
self.button = -1
|
| 48 |
+
self.new_hand()
|
| 49 |
+
|
| 50 |
+
def new_hand(self):
|
| 51 |
+
env, n = self.env, self.n
|
| 52 |
+
self.button = (self.button + 1) % n
|
| 53 |
+
env.reset(n_override=n, stacks_override=torch.full((1, n), self.stack0))
|
| 54 |
+
# place the dealer button deterministically (rotate each hand) and re-post blinds
|
| 55 |
+
env.button[0] = self.button
|
| 56 |
+
env.stack[0, :n] = self.stack0
|
| 57 |
+
env.bet.zero_(); env.contrib.zero_(); env.st_contrib.zero_()
|
| 58 |
+
sb = self.button if n == 2 else (self.button + 1) % n
|
| 59 |
+
bb = (sb + 1) % n
|
| 60 |
+
for s, a in ((sb, 0.5), (bb, 1.0)):
|
| 61 |
+
env.stack[0, s] -= a; env.bet[0, s] += a; env.contrib[0, s] += a; env.st_contrib[0, s, 0] += a
|
| 62 |
+
env.max_bet[0] = 1.0
|
| 63 |
+
env.cur[0] = env._next_need(torch.tensor([bb]), env._need())[0][0]
|
| 64 |
+
self.sb, self.bb = sb, bb
|
| 65 |
+
self.last = [""] * n
|
| 66 |
+
self.last[sb], self.last[bb] = "SB 0.5", "BB 1"
|
| 67 |
+
self.log = [f"— Mão #{self.hands + 1} — botão: {self.name(self.button)}"]
|
| 68 |
+
self.think = None
|
| 69 |
+
self.result = None
|
| 70 |
+
self.street_seen = 0
|
| 71 |
+
|
| 72 |
+
def name(self, s):
|
| 73 |
+
return "Você" if s == self.hero else f"IA {s + 1}"
|
| 74 |
+
|
| 75 |
+
# ---------------------------------------------------------------- actions
|
| 76 |
+
def probs_for_current(self):
|
| 77 |
+
o = self.env.obs()
|
| 78 |
+
pr = self.ai.probs(o)[0]
|
| 79 |
+
return pr, o
|
| 80 |
+
|
| 81 |
+
def describe(self, a, custom=None):
|
| 82 |
+
env = self.env
|
| 83 |
+
p = int(env.cur[0])
|
| 84 |
+
bet_p = env.bet[0, p].item()
|
| 85 |
+
stk = env.stack[0, p].item()
|
| 86 |
+
to_call = max(env.max_bet[0].item() - bet_p, 0.0)
|
| 87 |
+
if a == 0:
|
| 88 |
+
return "fold"
|
| 89 |
+
if a == 1:
|
| 90 |
+
if to_call <= 1e-9:
|
| 91 |
+
return "check"
|
| 92 |
+
return f"call {fmt(min(to_call, stk))}" + (" (all-in)" if stk <= to_call + 1e-9 else "")
|
| 93 |
+
if a == 9:
|
| 94 |
+
return f"ALL-IN {fmt(bet_p + stk)}"
|
| 95 |
+
if a == N_ACTIONS:
|
| 96 |
+
to = max(custom, env.max_bet[0].item() + env.min_raise[0].item())
|
| 97 |
+
else:
|
| 98 |
+
to = env._raise_targets(env.cur)[0, a].item()
|
| 99 |
+
to = min(to, bet_p + stk)
|
| 100 |
+
verb = "bet" if env.max_bet[0].item() <= 1e-9 else "raise para"
|
| 101 |
+
return f"{verb} {fmt(to)}" + (" (all-in)" if to >= bet_p + stk - 1e-9 else "")
|
| 102 |
+
|
| 103 |
+
def apply(self, a, custom=None):
|
| 104 |
+
env = self.env
|
| 105 |
+
p = int(env.cur[0])
|
| 106 |
+
street = int(env.street[0])
|
| 107 |
+
txt = self.describe(a, custom)
|
| 108 |
+
self.last[p] = txt
|
| 109 |
+
self.log.append(f"{self.name(p)}: {txt}")
|
| 110 |
+
fin, delta = env.step(torch.tensor([a]), custom_to=None if custom is None else torch.tensor([float(custom)]))
|
| 111 |
+
if not fin[0] and int(env.street[0]) != street:
|
| 112 |
+
st = int(env.street[0])
|
| 113 |
+
self.last = [""] * self.n
|
| 114 |
+
cards = " ".join(card_str(c) for c in env.board[0, :NREV[st]].tolist())
|
| 115 |
+
self.log.append(f"— {STREETS[st]}: {cards}")
|
| 116 |
+
if fin[0]:
|
| 117 |
+
self.finish(delta[0])
|
| 118 |
+
|
| 119 |
+
def finish(self, delta):
|
| 120 |
+
env, n = self.env, self.n
|
| 121 |
+
self.hands += 1
|
| 122 |
+
live = [s for s in range(n) if not env.folded[0, s]]
|
| 123 |
+
board = env.board[0].tolist()
|
| 124 |
+
showdown = len(live) > 1
|
| 125 |
+
hands = {}
|
| 126 |
+
if showdown:
|
| 127 |
+
for s in live:
|
| 128 |
+
sc = self.ev.eval_k(torch.tensor([env.hole[0, s].tolist() + board]))
|
| 129 |
+
hands[s] = CAT_NAMES[int(self.ev.category(sc)[0])]
|
| 130 |
+
self.log.append(f"— Showdown: {' '.join(card_str(c) for c in board)}")
|
| 131 |
+
winners = []
|
| 132 |
+
for s in range(n):
|
| 133 |
+
d = delta[s].item()
|
| 134 |
+
self.profit[s] += d
|
| 135 |
+
if d > 1e-9:
|
| 136 |
+
winners.append(s)
|
| 137 |
+
self.log.append(f"{self.name(s)} ganha {fmt(d + env.contrib[0, s].item())}"
|
| 138 |
+
+ (f" com {hands[s]}" if s in hands else ""))
|
| 139 |
+
self.result = dict(winners=winners, hands={str(k): v for k, v in hands.items()}, showdown=showdown,
|
| 140 |
+
delta=[round(delta[s].item(), 2) for s in range(n)])
|
| 141 |
+
|
| 142 |
+
def ai_step(self):
|
| 143 |
+
env = self.env
|
| 144 |
+
if env.done[0] or int(env.cur[0]) == self.hero:
|
| 145 |
+
return
|
| 146 |
+
p = int(env.cur[0])
|
| 147 |
+
pr, o = self.probs_for_current()
|
| 148 |
+
a = int(torch.distributions.Categorical(probs=pr).sample())
|
| 149 |
+
self.think = self.think_info(p, pr, a)
|
| 150 |
+
self.apply(a)
|
| 151 |
+
|
| 152 |
+
def hero_act(self, kind, amount=None):
|
| 153 |
+
env = self.env
|
| 154 |
+
if env.done[0] or int(env.cur[0]) != self.hero:
|
| 155 |
+
return
|
| 156 |
+
L = env.legal()[0]
|
| 157 |
+
if kind == "fold":
|
| 158 |
+
a, c = (0 if L[0] else 1), None
|
| 159 |
+
elif kind == "call":
|
| 160 |
+
a, c = 1, None
|
| 161 |
+
elif kind == "allin":
|
| 162 |
+
a, c = (9 if L[9] else 1), None
|
| 163 |
+
else:
|
| 164 |
+
if not L[9]:
|
| 165 |
+
a, c = 1, None
|
| 166 |
+
else:
|
| 167 |
+
a, c = N_ACTIONS, float(amount)
|
| 168 |
+
if c >= env.bet[0, self.hero].item() + env.stack[0, self.hero].item() - 1e-9:
|
| 169 |
+
a, c = 9, None
|
| 170 |
+
self.apply(a, c)
|
| 171 |
+
|
| 172 |
+
def think_info(self, p, pr, chosen=None):
|
| 173 |
+
env = self.env
|
| 174 |
+
merged = {}
|
| 175 |
+
for i in range(N_ACTIONS):
|
| 176 |
+
if pr[i] < 1e-4:
|
| 177 |
+
continue
|
| 178 |
+
lab = self.describe(i) # different abstract sizes can map to the same real amount
|
| 179 |
+
m = merged.setdefault(lab, dict(label=lab, p=0.0, chosen=False))
|
| 180 |
+
m["p"] += pr[i].item()
|
| 181 |
+
m["chosen"] |= (i == chosen)
|
| 182 |
+
opts = [dict(m, p=round(m["p"], 3)) for m in merged.values() if m["p"] >= 0.005 or m["chosen"]]
|
| 183 |
+
opts.sort(key=lambda d: -d["p"])
|
| 184 |
+
o = env.obs()
|
| 185 |
+
return dict(seat=p, name=self.name(p), options=opts, equity=round(o["glob"][0, 4 + 18].item(), 3),
|
| 186 |
+
street=STREETS[int(env.street[0])])
|
| 187 |
+
|
| 188 |
+
# ---------------------------------------------------------------- state
|
| 189 |
+
def state(self, hint=False):
|
| 190 |
+
env, n = self.env, self.n
|
| 191 |
+
st = int(env.street[0])
|
| 192 |
+
done = bool(env.done[0])
|
| 193 |
+
cur = -1 if done else int(env.cur[0])
|
| 194 |
+
seats = []
|
| 195 |
+
for s in range(n):
|
| 196 |
+
show = (s == self.hero) or self.reveal or (done and self.result and self.result["showdown"]
|
| 197 |
+
and not env.folded[0, s])
|
| 198 |
+
seats.append(dict(
|
| 199 |
+
seat=s, name=self.name(s), stack=round(env.stack[0, s].item(), 2), bet=round(env.bet[0, s].item(), 2),
|
| 200 |
+
folded=bool(env.folded[0, s]), allin=bool(env.allin[0, s]),
|
| 201 |
+
cards=[card_str(c) for c in env.hole[0, s].tolist()] if show else None,
|
| 202 |
+
last=self.last[s], button=s == self.button, sb=s == self.sb, bb=s == self.bb,
|
| 203 |
+
profit=round(self.profit[s], 2), hero=s == self.hero))
|
| 204 |
+
d = dict(n=n, hero=self.hero, street=STREETS[st], board=[card_str(c) for c in env.board[0, :NREV[st]].tolist()]
|
| 205 |
+
if not done else [card_str(c) for c in env.board[0, :NREV[st] if not (self.result and self.result["showdown"]) else 5].tolist()],
|
| 206 |
+
pot=round(env.contrib[0].sum().item(), 2), cur=cur, done=done, seats=seats, log=self.log[-60:],
|
| 207 |
+
think=self.think, result=self.result, hands=self.hands, stack0=self.stack0)
|
| 208 |
+
if not done and cur == self.hero:
|
| 209 |
+
bet_p = env.bet[0, cur].item()
|
| 210 |
+
stk = env.stack[0, cur].item()
|
| 211 |
+
L = env.legal()[0]
|
| 212 |
+
to_call = max(env.max_bet[0].item() - bet_p, 0.0)
|
| 213 |
+
pot = env.contrib[0].sum().item()
|
| 214 |
+
d["hero_opts"] = dict(
|
| 215 |
+
to_call=round(min(to_call, stk), 2), can_fold=bool(L[0]), can_raise=bool(L[9]),
|
| 216 |
+
min_to=round(min(env.max_bet[0].item() + env.min_raise[0].item(), bet_p + stk), 2),
|
| 217 |
+
max_to=round(bet_p + stk, 2), pot=round(pot, 2), max_bet=round(env.max_bet[0].item(), 2),
|
| 218 |
+
bet_word="Bet" if env.max_bet[0].item() <= 1e-9 else "Raise")
|
| 219 |
+
if hint:
|
| 220 |
+
pr, _ = self.probs_for_current()
|
| 221 |
+
d["hint"] = self.think_info(cur, pr)
|
| 222 |
+
return d
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class Handler(BaseHTTPRequestHandler):
|
| 226 |
+
game = None
|
| 227 |
+
|
| 228 |
+
def log_message(self, *a):
|
| 229 |
+
pass
|
| 230 |
+
|
| 231 |
+
def _send(self, code, body, ctype="application/json"):
|
| 232 |
+
b = body.encode() if isinstance(body, str) else body
|
| 233 |
+
self.send_response(code)
|
| 234 |
+
self.send_header("Content-Type", ctype)
|
| 235 |
+
self.send_header("Content-Length", str(len(b)))
|
| 236 |
+
self.end_headers()
|
| 237 |
+
self.wfile.write(b)
|
| 238 |
+
|
| 239 |
+
def do_GET(self):
|
| 240 |
+
if self.path.split("?")[0] in ("/", "/index.html"):
|
| 241 |
+
with open(os.path.join(HERE, "web", "index.html"), "rb") as f:
|
| 242 |
+
self._send(200, f.read(), "text/html; charset=utf-8")
|
| 243 |
+
else:
|
| 244 |
+
self._send(404, "not found", "text/plain")
|
| 245 |
+
|
| 246 |
+
def do_POST(self):
|
| 247 |
+
n = int(self.headers.get("Content-Length", 0) or 0)
|
| 248 |
+
req = json.loads(self.rfile.read(n) or b"{}")
|
| 249 |
+
g = self.game
|
| 250 |
+
try:
|
| 251 |
+
with g.lock:
|
| 252 |
+
if self.path == "/api/new_game":
|
| 253 |
+
g.new_game(req.get("players", 6), req.get("stack", 100), req.get("mode", "play"), req.get("reveal", False))
|
| 254 |
+
elif g.env is None:
|
| 255 |
+
g.new_game()
|
| 256 |
+
elif self.path == "/api/next_hand":
|
| 257 |
+
g.new_hand()
|
| 258 |
+
elif self.path == "/api/ai_step":
|
| 259 |
+
g.ai_step()
|
| 260 |
+
elif self.path == "/api/act":
|
| 261 |
+
g.hero_act(req.get("kind"), req.get("amount"))
|
| 262 |
+
elif self.path != "/api/state":
|
| 263 |
+
return self._send(404, "{}")
|
| 264 |
+
self._send(200, json.dumps(g.state(hint=bool(req.get("hint")))))
|
| 265 |
+
except Exception as e: # report errors to the page instead of crashing
|
| 266 |
+
import traceback
|
| 267 |
+
traceback.print_exc()
|
| 268 |
+
self._send(500, json.dumps(dict(error=str(e))))
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def main():
|
| 272 |
+
ap = argparse.ArgumentParser()
|
| 273 |
+
ap.add_argument("--model", default=None, help="caminho do .pt (padrão: model.pt do Hugging Face)")
|
| 274 |
+
ap.add_argument("--port", type=int, default=8765)
|
| 275 |
+
ap.add_argument("--no-browser", action="store_true")
|
| 276 |
+
a = ap.parse_args()
|
| 277 |
+
print("carregando modelo e avaliador de mãos...")
|
| 278 |
+
ai = PokerAI.load(a.model)
|
| 279 |
+
Handler.game = Game(ai, HandEvaluator("cpu"))
|
| 280 |
+
url = f"http://localhost:{a.port}"
|
| 281 |
+
srv = ThreadingHTTPServer(("127.0.0.1", a.port), Handler)
|
| 282 |
+
print(f"pronto: {url} (Ctrl+C para sair)")
|
| 283 |
+
if not a.no_browser:
|
| 284 |
+
webbrowser.open(url)
|
| 285 |
+
srv.serve_forever()
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
if __name__ == "__main__":
|
| 289 |
+
main()
|
web/index.html
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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>Poker AI — mesa</title>
|
| 7 |
+
<style>
|
| 8 |
+
:root{
|
| 9 |
+
--bg:#0d1117; --panel:#161b22; --line:#2a313c; --text:#e6edf3; --muted:#8b949e;
|
| 10 |
+
--felt:#14613b; --felt2:#0d4a2c; --rail:#3b2414; --gold:#e3b341; --accent:#3fb950; --red:#f85149; --blue:#58a6ff;
|
| 11 |
+
}
|
| 12 |
+
*{box-sizing:border-box}
|
| 13 |
+
body{margin:0;background:var(--bg);color:var(--text);font:14px/1.4 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;height:100vh;display:flex;flex-direction:column}
|
| 14 |
+
header{display:flex;gap:14px;align-items:center;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--panel);flex-wrap:wrap}
|
| 15 |
+
header h1{font-size:16px;margin:0 8px 0 0;letter-spacing:.3px}
|
| 16 |
+
header h1 span{color:var(--gold)}
|
| 17 |
+
label{color:var(--muted);font-size:12px;display:flex;align-items:center;gap:6px}
|
| 18 |
+
input[type=number]{width:64px}
|
| 19 |
+
input,select,button{font:inherit;color:var(--text);background:#0d1117;border:1px solid var(--line);border-radius:6px;padding:5px 8px}
|
| 20 |
+
button{cursor:pointer;background:#21262d}
|
| 21 |
+
button:hover{border-color:var(--muted)}
|
| 22 |
+
button.primary{background:#238636;border-color:#2ea043}
|
| 23 |
+
button.danger{background:#6e1c1c;border-color:#a32b2b}
|
| 24 |
+
button:disabled{opacity:.4;cursor:default}
|
| 25 |
+
.stats{margin-left:auto;display:flex;gap:16px;font-size:13px}
|
| 26 |
+
.stats b{font-variant-numeric:tabular-nums}
|
| 27 |
+
main{flex:1;display:flex;min-height:0}
|
| 28 |
+
#tablewrap{flex:1;position:relative;min-width:0}
|
| 29 |
+
#table{position:absolute;left:50%;top:46%;transform:translate(-50%,-50%);width:min(78%,1000px);aspect-ratio:2.05/1;border-radius:50%/50%;
|
| 30 |
+
background:radial-gradient(ellipse at center,var(--felt) 0%,var(--felt2) 75%);border:14px solid var(--rail);box-shadow:0 0 0 3px #1f130a,0 20px 60px rgba(0,0,0,.6), inset 0 0 60px rgba(0,0,0,.45)}
|
| 31 |
+
#center{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);text-align:center}
|
| 32 |
+
#board{display:flex;gap:6px;justify-content:center;min-height:76px}
|
| 33 |
+
#pot{margin-top:8px;font-weight:600;color:#fff;background:rgba(0,0,0,.35);display:inline-block;padding:3px 12px;border-radius:20px}
|
| 34 |
+
#street{color:#cfe8d6;font-size:12px;margin-bottom:6px;letter-spacing:1px;text-transform:uppercase}
|
| 35 |
+
.card{width:50px;height:72px;border-radius:7px;background:#fdfdfd;color:#111;display:flex;flex-direction:column;align-items:center;justify-content:center;
|
| 36 |
+
font-weight:700;box-shadow:0 2px 6px rgba(0,0,0,.5);font-size:20px;line-height:1}
|
| 37 |
+
.card .s{font-size:22px}
|
| 38 |
+
.card.red{color:#d1242f}
|
| 39 |
+
.card.back{background:repeating-linear-gradient(45deg,#1f4f9a 0 6px,#173d78 6px 12px);border:2px solid #fff}
|
| 40 |
+
.card.small{width:34px;height:48px;font-size:14px;border-radius:5px}
|
| 41 |
+
.card.small .s{font-size:15px}
|
| 42 |
+
.card.tiny{width:27px;height:38px;font-size:12px;border-radius:4px}
|
| 43 |
+
.card.tiny .s{font-size:12px}
|
| 44 |
+
.seat.compact .cards{min-height:38px}
|
| 45 |
+
.seat.compact .box{padding:2px 4px}
|
| 46 |
+
.seat.compact .nm,.seat.compact .stk{font-size:11px}
|
| 47 |
+
.seat{position:absolute;transform:translate(-50%,-50%);width:126px;text-align:center;transition:opacity .2s}
|
| 48 |
+
.seat .box{background:rgba(13,17,23,.92);border:2px solid var(--line);border-radius:10px;padding:4px 6px}
|
| 49 |
+
.seat.acting .box{border-color:var(--gold);box-shadow:0 0 14px rgba(227,179,65,.6)}
|
| 50 |
+
.seat.hero .box{border-color:var(--blue)}
|
| 51 |
+
.seat.hero.acting .box{border-color:var(--gold)}
|
| 52 |
+
.seat.folded{opacity:.38}
|
| 53 |
+
.seat.winner .box{border-color:var(--accent);box-shadow:0 0 18px rgba(63,185,80,.7)}
|
| 54 |
+
.seat .nm{font-weight:600;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
| 55 |
+
.seat .stk{font-variant-numeric:tabular-nums;color:var(--gold);font-size:12px}
|
| 56 |
+
.seat .cards{display:flex;gap:3px;justify-content:center;margin-bottom:3px;min-height:48px}
|
| 57 |
+
.seat .act{font-size:11px;color:#cfe8d6;min-height:15px;white-space:nowrap}
|
| 58 |
+
.seat .hn{font-size:11px;color:var(--accent)}
|
| 59 |
+
.seat .profit{font-size:10px;color:var(--muted)}
|
| 60 |
+
.chip{position:absolute;transform:translate(-50%,-50%);background:#f0f0f0;color:#111;border-radius:12px;padding:1px 8px;font-size:12px;font-weight:700;
|
| 61 |
+
border:3px dashed #c0392b;white-space:nowrap}
|
| 62 |
+
.dealer{display:inline-block;background:#fff;color:#000;border-radius:50%;width:17px;height:17px;font-size:10px;line-height:17px;font-weight:800;margin-left:4px}
|
| 63 |
+
.tag{font-size:9px;color:var(--muted);margin-left:3px}
|
| 64 |
+
#controls{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);display:flex;gap:8px;align-items:center;background:var(--panel);
|
| 65 |
+
border:1px solid var(--line);border-radius:12px;padding:10px 12px;flex-wrap:wrap;justify-content:center;max-width:95%}
|
| 66 |
+
#controls .big{font-size:15px;padding:9px 16px;min-width:96px}
|
| 67 |
+
#amt{width:80px}
|
| 68 |
+
#slider{width:160px}
|
| 69 |
+
aside{width:340px;border-left:1px solid var(--line);background:var(--panel);display:flex;flex-direction:column;min-height:0}
|
| 70 |
+
aside h2{font-size:13px;text-transform:uppercase;letter-spacing:1px;color:var(--muted);margin:14px 14px 8px}
|
| 71 |
+
#think{padding:0 14px 6px}
|
| 72 |
+
.bar{display:flex;align-items:center;gap:8px;margin:4px 0;font-size:12px}
|
| 73 |
+
.bar .lbl{width:120px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
| 74 |
+
.bar .track{flex:1;height:14px;background:#0d1117;border-radius:4px;overflow:hidden;border:1px solid var(--line)}
|
| 75 |
+
.bar .fill{height:100%;background:var(--blue)}
|
| 76 |
+
.bar.chosen .fill{background:var(--gold)}
|
| 77 |
+
.bar.chosen .lbl{color:var(--gold);font-weight:700}
|
| 78 |
+
.bar .pct{width:42px;text-align:right;font-variant-numeric:tabular-nums}
|
| 79 |
+
.eq{font-size:12px;color:var(--muted);margin-top:6px}
|
| 80 |
+
#log{flex:1;overflow:auto;padding:0 14px 14px;font-size:12px;font-family:ui-monospace,Consolas,monospace;color:#c9d1d9}
|
| 81 |
+
#log div{padding:1px 0}
|
| 82 |
+
#log .sep{color:var(--gold);margin-top:6px}
|
| 83 |
+
#msg{position:absolute;left:50%;top:12px;transform:translateX(-50%);background:rgba(0,0,0,.7);padding:6px 14px;border-radius:8px;display:none}
|
| 84 |
+
</style>
|
| 85 |
+
</head>
|
| 86 |
+
<body>
|
| 87 |
+
<header>
|
| 88 |
+
<h1>♠ Poker <span>AI</span></h1>
|
| 89 |
+
<label>Jogadores <input id="players" type="number" min="2" max="23" value="6"></label>
|
| 90 |
+
<label>Stack (bb) <input id="stack" type="number" min="5" max="1000" value="100"></label>
|
| 91 |
+
<label>Modo <select id="mode"><option value="play">Jogar contra a IA</option><option value="watch">Assistir IA vs IA</option></select></label>
|
| 92 |
+
<label><input id="reveal" type="checkbox"> Mostrar cartas das IAs</label>
|
| 93 |
+
<label><input id="hint" type="checkbox"> Dica da IA na minha vez</label>
|
| 94 |
+
<label>Velocidade <input id="speed" type="range" min="100" max="2500" value="900" step="100" style="width:90px"></label>
|
| 95 |
+
<button class="primary" id="newgame">Novo jogo</button>
|
| 96 |
+
<div class="stats">
|
| 97 |
+
<div>Mãos: <b id="hands">0</b></div>
|
| 98 |
+
<div id="pstat">Seu resultado: <b id="profit">0</b> bb</div>
|
| 99 |
+
<div id="bbstat">bb/100: <b id="bb100">—</b></div>
|
| 100 |
+
</div>
|
| 101 |
+
</header>
|
| 102 |
+
<main>
|
| 103 |
+
<div id="tablewrap">
|
| 104 |
+
<div id="table"><div id="center"><div id="street"></div><div id="board"></div><div id="pot"></div></div></div>
|
| 105 |
+
<div id="seats"></div>
|
| 106 |
+
<div id="msg"></div>
|
| 107 |
+
<div id="controls"></div>
|
| 108 |
+
</div>
|
| 109 |
+
<aside>
|
| 110 |
+
<h2>🧠 Cérebro da IA</h2>
|
| 111 |
+
<div id="think"><div class="eq">A última decisão da IA aparece aqui.</div></div>
|
| 112 |
+
<h2>Histórico</h2>
|
| 113 |
+
<div id="log"></div>
|
| 114 |
+
</aside>
|
| 115 |
+
</main>
|
| 116 |
+
<script>
|
| 117 |
+
const $ = id => document.getElementById(id);
|
| 118 |
+
let S = null, busy = false, timer = null;
|
| 119 |
+
const SUIT = {c:'♣', d:'♦', h:'♥', s:'♠'};
|
| 120 |
+
|
| 121 |
+
async function api(path, body={}) {
|
| 122 |
+
body.hint = $('hint').checked;
|
| 123 |
+
const r = await fetch(path, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body)});
|
| 124 |
+
const j = await r.json();
|
| 125 |
+
if (j.error) { flash('Erro: ' + j.error); throw new Error(j.error); }
|
| 126 |
+
return j;
|
| 127 |
+
}
|
| 128 |
+
function flash(t){ const m=$('msg'); m.textContent=t; m.style.display='block'; setTimeout(()=>m.style.display='none',2500); }
|
| 129 |
+
|
| 130 |
+
function cardHTML(c, small) {
|
| 131 |
+
const sz = small === 'tiny' ? 'tiny' : (small ? 'small' : '');
|
| 132 |
+
if (!c) return `<div class="card back ${sz}"></div>`;
|
| 133 |
+
const r = c[0] === 'T' ? '10' : c[0], s = c[1];
|
| 134 |
+
return `<div class="card ${sz} ${(s==='h'||s==='d')?'red':''}"><div>${r}</div><div class="s">${SUIT[s]}</div></div>`;
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
function seatPos(i, n, hero) {
|
| 138 |
+
// hero (or seat 0) at the bottom centre, others clockwise around the ellipse
|
| 139 |
+
const base = hero >= 0 ? hero : 0;
|
| 140 |
+
const k = (i - base + n) % n;
|
| 141 |
+
const ang = Math.PI/2 + 2*Math.PI*k/n; // start at bottom
|
| 142 |
+
return {x: 50 + 44*Math.cos(ang), y: 46 + 39*Math.sin(ang), cx: 50 + 27*Math.cos(ang), cy: 46 + 23*Math.sin(ang)};
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
function render() {
|
| 146 |
+
if (!S) return;
|
| 147 |
+
const wrap = $('tablewrap').getBoundingClientRect();
|
| 148 |
+
const tb = $('table').getBoundingClientRect();
|
| 149 |
+
$('street').textContent = S.done ? 'Fim da mão' : S.street;
|
| 150 |
+
$('board').innerHTML = S.board.map(c => cardHTML(c)).join('') + Array(5 - S.board.length).fill('<div class="card" style="opacity:.08"></div>').join('');
|
| 151 |
+
$('pot').textContent = `Pote: ${S.pot} bb`;
|
| 152 |
+
const n = S.n, small = n > 10, csz = n > 10 ? 'tiny' : true;
|
| 153 |
+
let html = '';
|
| 154 |
+
const winners = new Set(S.result ? S.result.winners : []);
|
| 155 |
+
S.seats.forEach(s => {
|
| 156 |
+
const p = seatPos(s.seat, n, S.hero);
|
| 157 |
+
// map ellipse percentages to table rect (seats slightly outside the felt)
|
| 158 |
+
const x = tb.left - wrap.left + tb.width * (0.5 + (p.x-50)/100*(small?1.16:1.12));
|
| 159 |
+
const y = tb.top - wrap.top + tb.height * (0.5 + (p.y-46)/100*1.25);
|
| 160 |
+
const cls = ['seat', small?'compact':'', s.hero?'hero':'', s.folded?'folded':'', (S.cur===s.seat)?'acting':'', winners.has(s.seat)?'winner':''].join(' ');
|
| 161 |
+
const cards = s.folded && !s.cards ? '' : (s.cards ? s.cards.map(c=>cardHTML(c,csz)).join('') : cardHTML(null,csz)+cardHTML(null,csz));
|
| 162 |
+
const hn = S.result && S.result.hands[s.seat] ? `<div class="hn">${S.result.hands[s.seat]}</div>` : '';
|
| 163 |
+
const delta = S.result ? S.result.delta[s.seat] : null;
|
| 164 |
+
const w = n > 16 ? 84 : (small ? 96 : 126);
|
| 165 |
+
html += `<div class="${cls}" style="left:${x}px;top:${y}px;width:${w}px">
|
| 166 |
+
<div class="cards">${cards}</div>
|
| 167 |
+
<div class="box">
|
| 168 |
+
<div class="nm">${s.name}${s.button?'<span class="dealer">D</span>':''}${s.sb?'<span class="tag">SB</span>':''}${s.bb?'<span class="tag">BB</span>':''}</div>
|
| 169 |
+
<div class="stk">${s.allin && !S.done ? 'ALL-IN' : s.stack + ' bb'}</div>
|
| 170 |
+
<div class="act">${delta!==null && Math.abs(delta)>0.001 ? (delta>0?'+':'')+delta+' bb' : (s.folded?'fold':s.last)}</div>
|
| 171 |
+
${hn}
|
| 172 |
+
</div></div>`;
|
| 173 |
+
if (s.bet > 0 && !S.done) {
|
| 174 |
+
const cx = tb.left - wrap.left + tb.width * (0.5 + (p.cx-50)/100);
|
| 175 |
+
const cy = tb.top - wrap.top + tb.height * (0.5 + (p.cy-46)/100);
|
| 176 |
+
html += `<div class="chip" style="left:${cx}px;top:${cy}px">${s.bet}</div>`;
|
| 177 |
+
}
|
| 178 |
+
});
|
| 179 |
+
$('seats').innerHTML = html;
|
| 180 |
+
// stats
|
| 181 |
+
$('hands').textContent = S.hands;
|
| 182 |
+
if (S.hero >= 0) {
|
| 183 |
+
const pr = S.seats[S.hero].profit;
|
| 184 |
+
$('profit').textContent = (pr>0?'+':'') + pr.toFixed(1);
|
| 185 |
+
$('profit').style.color = pr >= 0 ? 'var(--accent)' : 'var(--red)';
|
| 186 |
+
$('bb100').textContent = S.hands ? (100*pr/S.hands).toFixed(0) : '—';
|
| 187 |
+
$('pstat').style.display = $('bbstat').style.display = '';
|
| 188 |
+
} else { $('pstat').style.display = $('bbstat').style.display = 'none'; }
|
| 189 |
+
// brain panel
|
| 190 |
+
const T = S.hint || S.think;
|
| 191 |
+
if (T) {
|
| 192 |
+
const title = S.hint ? `O que a IA faria no seu lugar (${T.street})` : `${T.name} pensou (${T.street}):`;
|
| 193 |
+
$('think').innerHTML = `<div style="margin-bottom:6px;font-weight:600">${title}</div>` +
|
| 194 |
+
T.options.map(o => `<div class="bar ${o.chosen?'chosen':''}"><div class="lbl">${o.label}</div><div class="track"><div class="fill" style="width:${(o.p*100).toFixed(1)}%"></div></div><div class="pct">${(o.p*100).toFixed(0)}%</div></div>`).join('') +
|
| 195 |
+
`<div class="eq">Equidade estimada vs mãos aleatórias dos oponentes vivos: ${(T.equity*100).toFixed(0)}%</div>`;
|
| 196 |
+
}
|
| 197 |
+
$('log').innerHTML = S.log.map(l => `<div class="${l.startsWith('—')?'sep':''}">${l}</div>`).join('');
|
| 198 |
+
$('log').scrollTop = 1e9;
|
| 199 |
+
controls();
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
function controls() {
|
| 203 |
+
const c = $('controls');
|
| 204 |
+
if (S.done) {
|
| 205 |
+
c.innerHTML = `<button class="primary big" id="next">Próxima mão ▶</button>`;
|
| 206 |
+
$('next').onclick = nextHand;
|
| 207 |
+
return;
|
| 208 |
+
}
|
| 209 |
+
if (S.cur !== S.hero || !S.hero_opts) { c.innerHTML = `<span style="color:var(--muted)">${S.seats[S.cur].name} está pensando…</span>`; return; }
|
| 210 |
+
const o = S.hero_opts;
|
| 211 |
+
const callTxt = o.to_call > 0 ? `Call ${o.to_call}` : 'Check';
|
| 212 |
+
let h = `${o.can_fold ? '<button class="danger big" id="bf">Fold</button>' : ''}<button class="big" id="bc">${callTxt}</button>`;
|
| 213 |
+
if (o.can_raise) {
|
| 214 |
+
const potTo = x => Math.min(o.max_to, Math.max(o.min_to, +(o.max_bet + x*(o.pot + o.to_call)).toFixed(1)));
|
| 215 |
+
h += `<input id="slider" type="range" min="${o.min_to}" max="${o.max_to}" step="0.5" value="${o.min_to}">
|
| 216 |
+
<input id="amt" type="number" step="0.5" min="${o.min_to}" max="${o.max_to}" value="${o.min_to}">
|
| 217 |
+
<button data-f="0.5" class="ps">½ pote</button><button data-f="0.75" class="ps">¾</button><button data-f="1" class="ps">Pote</button>
|
| 218 |
+
<button class="primary big" id="br">${o.bet_word}</button><button class="big" id="ba">All-in ${o.max_to}</button>`;
|
| 219 |
+
c.innerHTML = h;
|
| 220 |
+
$('slider').oninput = e => $('amt').value = e.target.value;
|
| 221 |
+
$('amt').oninput = e => $('slider').value = e.target.value;
|
| 222 |
+
document.querySelectorAll('.ps').forEach(b => b.onclick = () => { const v = potTo(+b.dataset.f); $('amt').value = v; $('slider').value = v; });
|
| 223 |
+
$('br').onclick = () => act('raise', +$('amt').value);
|
| 224 |
+
$('ba').onclick = () => act('allin');
|
| 225 |
+
} else c.innerHTML = h;
|
| 226 |
+
if (o.can_fold) $('bf').onclick = () => act('fold');
|
| 227 |
+
$('bc').onclick = () => act('call');
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
async function act(kind, amount) { if (busy) return; busy = true; try { S = await api('/api/act', {kind, amount}); render(); } finally { busy = false; } loop(); }
|
| 231 |
+
async function nextHand() { clearTimeout(timer); S = await api('/api/next_hand'); render(); loop(); }
|
| 232 |
+
|
| 233 |
+
function loop() {
|
| 234 |
+
clearTimeout(timer);
|
| 235 |
+
if (!S) return;
|
| 236 |
+
const speed = +$('speed').value;
|
| 237 |
+
if (S.done) { if (S.hero < 0) timer = setTimeout(nextHand, speed * 2.2); return; }
|
| 238 |
+
if (S.cur !== S.hero) timer = setTimeout(async () => { S = await api('/api/ai_step'); render(); loop(); }, speed);
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
$('newgame').onclick = async () => {
|
| 242 |
+
clearTimeout(timer);
|
| 243 |
+
S = await api('/api/new_game', {players: +$('players').value, stack: +$('stack').value, mode: $('mode').value, reveal: $('reveal').checked});
|
| 244 |
+
$('think').innerHTML = '<div class="eq">A última decisão da IA aparece aqui.</div>';
|
| 245 |
+
render(); loop();
|
| 246 |
+
};
|
| 247 |
+
$('hint').onchange = async () => { if (S) { S = await api('/api/state'); render(); } };
|
| 248 |
+
window.onresize = render;
|
| 249 |
+
// optional URL params: ?players=9&stack=100&mode=watch&reveal=1&hint=1&speed=500
|
| 250 |
+
const Q = new URLSearchParams(location.search);
|
| 251 |
+
['players','stack','speed'].forEach(k => { if (Q.has(k)) $(k).value = Q.get(k); });
|
| 252 |
+
if (Q.has('mode')) $('mode').value = Q.get('mode');
|
| 253 |
+
if (Q.get('reveal') === '1') $('reveal').checked = true;
|
| 254 |
+
if (Q.get('hint') === '1') $('hint').checked = true;
|
| 255 |
+
$('newgame').click();
|
| 256 |
+
</script>
|
| 257 |
+
</body>
|
| 258 |
+
</html>
|