retrucada 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/dist/retrucada.js +18 -0
- package/package.json +18 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rafael Franco
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# retrucada
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Truco 1×1 no terminal. A partida roda no servidor da [Retrucada](https://retrucada.com), vale o mesmo ranking do
|
|
4
|
+
site e dá para jogar contra o robô, contra quem estiver na fila ou com um amigo pelo código da sala.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npx retrucada
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Precisa do Node 20 ou mais novo. Na primeira vez você entra com o seu email (mandamos um código de 6 números); a
|
|
11
|
+
sessão fica salva em `~/.config/retrucada/`.
|
|
12
|
+
|
|
13
|
+
- **Paulista** (manilha pela vira) ou **mineiro** (manilhas fixas).
|
|
14
|
+
- **Robô** fácil, médio, difícil ou a rede neural, valendo nota.
|
|
15
|
+
- **Esc** esconde o jogo atrás de uma saída de testes qualquer; qualquer tecla volta.
|
|
16
|
+
- **q** ou **Ctrl-C** fecha e devolve o terminal como estava, sem a mesa na rolagem.
|
|
17
|
+
- Cores discretas por padrão; no menu dá para trocar para as do boteco. `NO_COLOR=1` tira as cores.
|
|
18
|
+
|
|
19
|
+
| Tecla | O que faz |
|
|
20
|
+
|---|---|
|
|
21
|
+
| ←→ ou 1 2 3 | escolhe a carta (o número já joga) |
|
|
22
|
+
| ⏎ ou espaço | joga a carta escolhida |
|
|
23
|
+
| t | truco, seis, nove, doze |
|
|
24
|
+
| a · r | aceita (quero) · corre |
|
|
25
|
+
| c | cobre a próxima carta |
|
|
26
|
+
| j | joga a mão de onze (ou de dez) |
|
|
27
|
+
| ? | força das cartas desta mão e as regras |
|
|
28
|
+
|
|
29
|
+
`npx retrucada --en` joga em inglês; `npx retrucada --logout` sai da conta neste computador.
|
|
30
|
+
|
|
31
|
+
## English
|
|
32
|
+
|
|
33
|
+
1-on-1 truco in your terminal, played on the Retrucada server: same leaderboard as the site, against the robot,
|
|
34
|
+
people in the queue or a friend with a room code. Run `npx retrucada --en` (Node 20+). Esc hides the game behind
|
|
35
|
+
some test output; q or Ctrl-C gives your terminal back as it was.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{readFileSync as Tt}from"node:fs";var X=["4","5","6","7","Q","J","K","A","2","3"],hn=["d","s","h","c"],ee=e=>e[0],U=e=>e[1];var nt=X.flatMap(e=>hn.map(n=>`${e}${n}`)),Ge=["7d","As","7h","4c"],we=e=>X[(X.indexOf(ee(e))+1)%X.length];function ze(e,n){if(e==="mineiro")return Ge;if(!n)return[];let t=we(n);return hn.map(r=>`${t}${r}`)}var gn=(e,n,t)=>ze(n,t).includes(e),tt={c:"\u2663",h:"\u2665",s:"\u2660",d:"\u2666"},_e=e=>`${ee(e)}${tt[U(e)]}`;var M=e=>e===0?1:0,_={paulista:[1,3,6,9,12],mineiro:[2,4,8,10,12]},bn=["","truco","seis","nove","doze"];var qe=(e,n)=>e.deck[n].c;function lt(e){let n=e.hand.pending?e.hand.pending.level+1:e.hand.level+1;return bn[n]??"raise"}function yn(e,n){switch(n.t){case"play":return`play ${qe(e,n.card)}${n.hidden?" hidden":""}`;case"raise":return lt(e);case"accept":return"accept";case"fold":return"fold";case"swap":return`swap ${qe(e,n.card)}`;case"discard":return`discard ${qe(e,n.card)}`;case"playHand":return"play_hand";case"resign":return"resign"}}var wn=["easy","medium","hard"];var Sn=[...wn,"neural"];import{mkdirSync as ct,readFileSync as dt,rmSync as ut,writeFileSync as ft}from"node:fs";import{homedir as pt}from"node:os";import{join as Ie}from"node:path";var xn=(process.env.RETRUCADA_API??"https://api.retrucada.com").replace(/\/$/,""),$n=Ie(process.env.XDG_CONFIG_HOME||Ie(pt(),".config"),"retrucada"),Ve=Ie($n,xn==="https://api.retrucada.com"?"terminal.json":"terminal-dev.json");function kn(){try{return JSON.parse(dt(Ve,"utf8"))}catch{return{}}}function Cn(e){try{ct($n,{recursive:!0,mode:448}),ft(Ve,JSON.stringify(e,null,2),{mode:384})}catch{}}var Rn=()=>ut(Ve,{force:!0}),N=class extends Error{constructor(t,r){super(r);this.status=t}status},Be=null,Tn="retrucada-terminal",ce=e=>{Be=e},An=e=>{Tn=`retrucada-terminal/${e}`};async function T(e,n,t){let r=await fetch(`${xn}${n}`,{method:e,headers:{"Content-Type":"application/json","User-Agent":Tn,...Be?{Authorization:`Bearer ${Be}`}:{}},body:t===void 0?void 0:JSON.stringify(t),signal:AbortSignal.timeout(35e3)}),o=await r.json().catch(()=>({}));if(!r.ok)throw new N(r.status,o.error??`HTTP ${r.status}`);return o}var y={loginStart:(e,n)=>T("POST","/v1/login/start",{email:e,lang:n}),loginVerify:(e,n)=>T("POST","/v1/login/verify",{email:e,code:n}),me:()=>T("GET","/v1/me"),setUsername:e=>T("POST","/v1/me/username",{username:e}),logout:()=>T("POST","/v1/me/logout"),newGame:e=>T("POST","/v1/games?raw=1",e),game:e=>T("GET",`/v1/games/${e}?raw=1`),move:(e,n)=>T("POST",`/v1/games/${e}/move?raw=1`,{move:n}),wait:(e,n)=>T("POST",`/v1/games/${e}/wait?raw=1`,{timeout_s:20,seen:n}),resign:e=>T("POST",`/v1/games/${e}/resign?raw=1`,{}),myGames:()=>T("GET","/v1/games")};var On=["discreto","boteco"],Mn={discreto:{dim:243,border:240,red:167,gold:179,me:108,opp:139,good:108,bad:167,back:239},boteco:{dim:244,accent:215,border:180,red:160,black:236,gold:172,me:114,opp:210,good:114,bad:203,face:230,back:174,backBg:88}},Ln=!0,h=Mn.discreto,En=e=>{Ln=e},De=e=>{h=Mn[e]};function g(e,n){if(!Ln||!e)return e;let t=[];return n.bold&&t.push("1"),n.fg!==void 0&&t.push(`38;5;${n.fg}`),n.bg!==void 0&&t.push(`48;5;${n.bg}`),t.length?`\x1B[${t.join(";")}m${e}\x1B[0m`:e}var d=e=>g(e,{fg:h.dim}),b=e=>g(e,{fg:h.accent,bold:!0}),We=e=>g(e,{bold:!0}),xe=e=>g(e,{fg:h.me,bold:!0}),ne=e=>g(e,{fg:h.opp,bold:!0}),Ke=e=>g(e,{fg:h.good,bold:!0}),q=e=>g(e,{fg:h.bad,bold:!0}),Fe=e=>g(e,{fg:h.gold,bold:!0});var mt=/\x1b\[[0-9;]*m/g,Y=e=>[...e.replace(mt,"")].length,k=(e,n)=>e+" ".repeat(Math.max(0,n-Y(e))),te=(e,n)=>{let t=Math.max(0,Math.floor((n-Y(e))/2));return k(" ".repeat(t)+e,n)},de=(e,n)=>[...e].length<=n?e:[...e].slice(0,Math.max(0,n-1)).join("")+"\u2026";function I(e,n){let t=[],r="";for(let o of e.split(/\s+/).filter(Boolean))r&&[...r].length+1+[...o].length>n?(t.push(r),r=o):r=r?`${r} ${o}`:o;return r&&t.push(r),t}function P(e,n=1){let t=Math.max(0,...e.map(i=>i.length)),r=e.map(i=>Math.max(0,...i.map(Y))),o=[];for(let i=0;i<t;i++)o.push(e.map((l,s)=>k(l[i]??"",r[s])).join(" ".repeat(n)));return o}var re=(e,n)=>[...Array(n).fill(""),...e],$e={c:"\u2663",h:"\u2665",s:"\u2660",d:"\u2666"},Ue=e=>U(e)==="h"||U(e)==="d",Hn=e=>$e[e],Ye=e=>g(`${ee(e)}${$e[U(e)]}`,{fg:Ue(e)?h.red:h.accent,bold:!0});function ke(e,n,t){let r=t.manilha?h.gold:h.border,o=t.faded?void 0:h.face,i=s=>g(s,{fg:r,bg:o,bold:t.manilha}),l=[i(`\u256D${"\u2500".repeat(n)}\u256E`)];for(let s of e)l.push(i("\u2502")+s+i("\u2502"));return l.push(i(`\u2570${"\u2500".repeat(n)}\u256F`)),l}function A(e,n,t,r=!1){let o=t.faded?void 0:h.face;return t.faded?g(e,{fg:h.dim}):g(e,{fg:n,bg:o,bold:r})}function J(e,n={}){let t=Ue(e)?h.red:h.black,r=ee(e),o=n.manilha?g("\u2605",{fg:h.gold,bg:n.faded?void 0:h.face,bold:!0}):A(" ",t,n);return ke([A(r,t,n,!0)+A(" ",t,n)+o,A(" ",t,n)+A($e[U(e)],t,n,!0)+A(" ",t,n),A(" ",t,n)+A(r,t,n,!0)],5,n)}function Je(e,n={}){let t=Ue(e)?h.red:h.black;return ke([A(ee(e),t,n,!0)+A(" ",t,n)+A($e[U(e)],t,n,!0)],3,n)}var Se=e=>g("\u2592".repeat(e),{fg:h.back,bg:h.backBg});function Nn(){return ke([Se(5),Se(5),Se(5)],5,{faded:!0})}function Qe(){return ke([Se(3)],3,{faded:!0})}function Pn(){let e=n=>g(n,{fg:h.border});return[e("\u256D\u2504\u2504\u2504\u256E"),e("\u2506 \u2506"),e("\u2570\u2504\u2504\u2504\u256F")]}function jn(e,n,t){let r=Math.min(n,15),o=Math.min(r,Math.round(e/n*r));return t("\u25CF".repeat(o))+d("\xB7".repeat(r-o))}var Ze={tagline:"truco 1\xD71 no terminal",style:"estilo",paulista:"paulista",mineiro:"mineiro",paulistaDesc:"manilha pela vira",mineiroDesc:"manilhas fixas",opponent:"advers\xE1rio",robot:e=>({easy:"rob\xF4 f\xE1cil",medium:"rob\xF4 m\xE9dio",hard:"rob\xF4 dif\xEDcil",neural:"rede neural"})[e],human:"pessoa",friendNew:"chamar amigo",friendJoin:"entrar com c\xF3digo",rated:"vale nota",unrated:"n\xE3o vale nota",queueDesc:"quem estiver na fila",colors:"cores",themes:{discreto:"discreto",boteco:"boteco"},language:"l\xEDngua",langName:"portugu\xEAs",play:"jogar",resume:"continuar",resumeDesc:(e,n)=>`contra ${e} \xB7 ${n}`,logout:"sair da conta",menuKeys:[["\u2191\u2193","escolher"],["\u2190\u2192","mudar"],["\u23CE","jogar"],["q","sair"]],loginIntro:"Entre com o seu email: mandamos um c\xF3digo de 6 n\xFAmeros.",loginWhy:"A partida roda no servidor da Retrucada e vale o mesmo ranking do site.",email:"email",code:"c\xF3digo",codeSent:e=>`Mandamos o c\xF3digo para ${e}.`,codeBack:"apague o c\xF3digo todo para trocar o email",usernameIntro:"Escolha o seu nome de jogador (de 3 a 16 letras, n\xFAmeros ou _). Ele n\xE3o muda depois.",username:"nome",sending:"mandando\u2026",apiErrors:{"bad-email":"Esse email n\xE3o parece certo. Confere e tenta de novo.","wait-to-resend":"Acabamos de mandar um c\xF3digo para esse email. Espera um minutinho.","email-failed":"N\xE3o conseguimos mandar o email agora. Tenta de novo daqui a pouco.","code-expired":"Esse c\xF3digo expirou. Apague e pe\xE7a um novo.","too-many-attempts":"Muitas tentativas com esse c\xF3digo. Apague e pe\xE7a um novo.","bad-code":"C\xF3digo errado. Confere no email e digita de novo.","name-invalid":"Nome inv\xE1lido: use de 3 a 16 letras, n\xFAmeros ou _.","name-taken":"Esse nome j\xE1 tem dono. Escolhe outro.","need-username":"Escolha um nome de jogador antes.","login-required":"Entre na sua conta para continuar.","not-found":"N\xE3o encontramos isso."},offline:"Sem conex\xE3o com o servidor. Tentando de novo\u2026",you:"voc\xEA",stake:"vale",vira:"vira",noVira:"sem vira",hiddenVira:"vira escondida",manilha:"manilha",manilhas:"manilhas",starts:"come\xE7a",round:["1\xAA","2\xAA","3\xAA"],tie:"cangou",levels:["","truco","seis","nove","doze"],covered:"coberta",yourTurn:"Sua vez.",firstLook:"Sua vez. Olhe as cartas.",asked:(e,n)=>`${e} pediu ${n}!`,onze:e=>`M\xE3o de ${e===11?"onze":"dez"}: olhe as cartas e decida.`,onzeOpp:(e,n)=>`${e} est\xE1 na m\xE3o de ${n===11?"onze":"dez"}\u2026`,thinking:e=>`${e} pensando`,waitingFor:e=>`vez de ${e}`,waitingAnswer:e=>`esperando ${e} responder`,secondsLeft:e=>`${e} s para jogar`,keys:{pick:"escolher",play:"jogar",cover:"cobrir",coverOn:"cobrindo",accept:"quero",fold:"correr",playHand:"jogar a m\xE3o",help:"ajuda",hide:"esconder",quit:"sair",next:"continuar",again:"de novo",menu:"menu"},ev:{played:(e,n)=>`${e} jogou ${n}`,coveredMine:e=>`voc\xEA cobriu ${e}`,coveredOpp:e=>`${e} jogou coberta`,raised:(e,n)=>`${e} pediu ${n}`,accepted:e=>`${e}: quero!`,folded:e=>`${e} correu`,playHand:e=>`${e} vai jogar a m\xE3o`,resigned:e=>`${e} desistiu`,roundWon:(e,n)=>`${e} levou a ${Ze.round[n]}`,roundTie:e=>`a ${Ze.round[e]} cangou`},handWon:e=>`Voc\xEA levou a m\xE3o: +${e}`,handLost:(e,n)=>`${e} levou a m\xE3o: +${n}`,handFold:e=>`(${e} correu)`,handNone:"Tr\xEAs cangadas: ningu\xE9m marca.",youWon:"Voc\xEA ganhou a partida!",youLost:"Voc\xEA perdeu a partida.",byResign:e=>`${e} desistiu.`,byAway:e=>e?"O seu tempo acabou.":"O tempo do advers\xE1rio acabou.",rating:(e,n,t)=>`nota ${e}: ${n} \u2192 ${t}`,sessionScore:(e,n)=>`hoje ${e} \xD7 ${n}`,confirmResign:"Desistir? A partida conta como derrota.",yesNo:"s sim \xB7 n n\xE3o",yes:"s",queue:"Procurando algu\xE9m para jogar\u2026",queueHint:"Pode levar uns minutos. esc esconde \xB7 q desiste da fila",friendCode:e=>`Passe o c\xF3digo ${e} para o seu amigo.`,friendHint:"O amigo entra com npx retrucada ou pelo site.",friendWait:"esc esconde \xB7 q fecha a sala",joinIntro:"Digite o c\xF3digo que o seu amigo passou.",joinCode:"c\xF3digo",cancelled:"Ningu\xE9m entrou a tempo. A sala foi fechada.",tooSmall:(e,n,t)=>`Aumente o terminal: precisa de ${t[0]}\xD7${t[1]}, est\xE1 ${e}\xD7${n}.`,help:{title:"Como jogar",now:"Nesta m\xE3o, da carta mais forte para a mais fraca:",then:"depois",suitNote:"Fora as manilhas o naipe n\xE3o conta: n\xFAmeros iguais cangam (empatam).",stakes:e=>`A m\xE3o vale ${e[0]}; truco ${e[1]}, seis ${e[2]}, nove ${e[3]}, doze ${e[4]}. Partida at\xE9 12.`,lines:["Melhor de 3 rodadas. Quem pede truco espera: o outro aceita, corre ou aumenta.","Da 2\xAA rodada em diante d\xE1 para cobrir: a carta vai virada e perde para qualquer outra."],keys:[["\u2190\u2192 ou 1 2 3","escolher a carta (o n\xFAmero j\xE1 joga)"],["\u23CE ou espa\xE7o","jogar a carta escolhida"],["t","pedir truco, seis, nove ou doze"],["a \xB7 r","aceitar (quero) \xB7 correr"],["c","cobrir a pr\xF3xima carta"],["j","jogar a m\xE3o de onze (ou de dez)"],["esc","esconder o jogo (qualquer tecla volta)"],["q","desistir ou sair"]],close:"qualquer tecla volta"},speech:{truco:["Truco!","Truco. Calculado.","Processando\u2026 TRUCO!"],seis:["Seis!","Seis! Recalculando."],nove:["Nove!","Nove! Probabilidade favor\xE1vel."],doze:["Doze!","Doze! Tudo ou nada."],quero:["Quero!","Quero. Aceito o risco."],corro:["Corro.","Corro. Retirada estrat\xE9gica.","Dessa vez n\xE3o, parceiro."],jogo:["Vou jogar!","Vou jogar. C\xE1lculo conclu\xEDdo."],ganhou_mao:["Conforme previsto.","Mais um ponto para a m\xE1quina."],perdeu_mao:["Erro de arredondamento.","Recalibrando."],vitoria:["Fim de jogo. Boa partida, humano."],derrota:["Voc\xEA venceu. Vou atualizar meus dados."]},usage:`retrucada: truco 1\xD71 no terminal, jogando no servidor da Retrucada
|
|
3
|
+
|
|
4
|
+
npx retrucada abre o jogo
|
|
5
|
+
npx retrucada --en em ingl\xEAs
|
|
6
|
+
npx retrucada --logout sai da conta neste computador
|
|
7
|
+
|
|
8
|
+
Esc esconde o jogo a qualquer momento; q ou Ctrl-C devolve o terminal como estava.
|
|
9
|
+
https://retrucada.com`},Xe={tagline:"1-on-1 truco in your terminal",style:"style",paulista:"paulista",mineiro:"mineiro",paulistaDesc:"manilha from the vira",mineiroDesc:"fixed manilhas",opponent:"opponent",robot:e=>({easy:"easy robot",medium:"medium robot",hard:"hard robot",neural:"neural net"})[e],human:"person",friendNew:"invite a friend",friendJoin:"join with code",rated:"rated",unrated:"unrated",queueDesc:"people in the queue",colors:"colors",themes:{discreto:"subtle",boteco:"bar"},language:"language",langName:"English",play:"play",resume:"continue",resumeDesc:(e,n)=>`vs ${e} \xB7 ${n}`,logout:"sign out",menuKeys:[["\u2191\u2193","choose"],["\u2190\u2192","change"],["\u23CE","play"],["q","quit"]],loginIntro:"Sign in with your email: we send a 6-digit code.",loginWhy:"Games run on the Retrucada server and count for the same leaderboard as the site.",email:"email",code:"code",codeSent:e=>`We sent the code to ${e}.`,codeBack:"delete the whole code to change the email",usernameIntro:"Pick your player name (3 to 16 letters, numbers or _). It does not change later.",username:"name",sending:"sending\u2026",apiErrors:{"bad-email":"That email doesn't look right. Check it and try again.","wait-to-resend":"We just sent a code to that email. Wait a minute.","email-failed":"We couldn't send the email right now. Try again in a bit.","code-expired":"That code expired. Delete it and ask for a new one.","too-many-attempts":"Too many tries with that code. Delete it and ask for a new one.","bad-code":"Wrong code. Check your email and type it again.","name-invalid":"Invalid name: use 3 to 16 letters, numbers or _.","name-taken":"That name is taken. Pick another.","need-username":"Pick a player name first.","login-required":"Sign in to continue.","not-found":"We couldn't find that."},offline:"No connection to the server. Trying again\u2026",you:"you",stake:"worth",vira:"vira",noVira:"no vira",hiddenVira:"vira hidden",manilha:"manilha",manilhas:"manilhas",starts:"leads",round:["1st","2nd","3rd"],tie:"tie",levels:["","truco","six","nine","twelve"],covered:"face down",yourTurn:"Your turn.",firstLook:"Your turn. Look at your cards.",asked:(e,n)=>`${e} called ${n}!`,onze:e=>`Hand of ${e===11?"eleven":"ten"}: look at your cards and decide.`,onzeOpp:(e,n)=>`${e} is on the hand of ${n===11?"eleven":"ten"}\u2026`,thinking:e=>`${e} thinking`,waitingFor:e=>`${e}'s turn`,waitingAnswer:e=>`waiting for ${e} to answer`,secondsLeft:e=>`${e} s to move`,keys:{pick:"choose",play:"play",cover:"face down",coverOn:"face down: on",accept:"accept",fold:"fold",playHand:"play the hand",help:"help",hide:"hide",quit:"quit",next:"continue",again:"again",menu:"menu"},ev:{played:(e,n)=>`${e} played ${n}`,coveredMine:e=>`you played ${e} face down`,coveredOpp:e=>`${e} played face down`,raised:(e,n)=>`${e} called ${n}`,accepted:e=>`${e}: accepted!`,folded:e=>`${e} folded`,playHand:e=>`${e} plays the hand`,resigned:e=>`${e} resigned`,roundWon:(e,n)=>`${e} took the ${Xe.round[n]} round`,roundTie:e=>`the ${Xe.round[e]} round tied`},handWon:e=>`You took the hand: +${e}`,handLost:(e,n)=>`${e} took the hand: +${n}`,handFold:e=>`(${e} folded)`,handNone:"Three ties: nobody scores.",youWon:"You won the match!",youLost:"You lost the match.",byResign:e=>`${e} resigned.`,byAway:e=>e?"You ran out of time.":"Your opponent ran out of time.",rating:(e,n,t)=>`${e} rating: ${n} \u2192 ${t}`,sessionScore:(e,n)=>`today ${e} \xD7 ${n}`,confirmResign:"Resign? The match counts as a loss.",yesNo:"y yes \xB7 n no",yes:"y",queue:"Looking for someone to play\u2026",queueHint:"It may take a few minutes. esc hides \xB7 q leaves the queue",friendCode:e=>`Give the code ${e} to your friend.`,friendHint:"Your friend joins with npx retrucada or on the site.",friendWait:"esc hides \xB7 q closes the room",joinIntro:"Type the code your friend gave you.",joinCode:"code",cancelled:"Nobody joined in time. The room was closed.",tooSmall:(e,n,t)=>`Make the terminal bigger: it needs ${t[0]}\xD7${t[1]}, it is ${e}\xD7${n}.`,help:{title:"How to play",now:"This hand, from the strongest card to the weakest:",then:"then",suitNote:"Outside the manilhas the suit doesn't count: equal ranks tie.",stakes:e=>`A hand is worth ${e[0]}; truco ${e[1]}, six ${e[2]}, nine ${e[3]}, twelve ${e[4]}. First to 12.`,lines:["Best of 3 rounds. After a truco call the other player accepts, folds or raises.","From the 2nd round on you may play face down: the card loses to any other."],keys:[["\u2190\u2192 or 1 2 3","choose a card (the number plays it)"],["\u23CE or space","play the chosen card"],["t","call truco, six, nine or twelve"],["a \xB7 r","accept \xB7 fold"],["c","play the next card face down"],["j","play the hand of eleven (or ten)"],["esc","hide the game (any key comes back)"],["q","resign or quit"]],close:"any key goes back"},speech:{truco:["Truco!","Truco. Calculated.","Processing\u2026 TRUCO!"],seis:["Six!","Six! Recalculating."],nove:["Nine!","Nine! Odds in my favor."],doze:["Twelve!","Twelve! All or nothing."],quero:["Accept!","Accept. Risk accepted."],corro:["I fold.","I fold. Strategic retreat.","Not this time, partner."],jogo:["I'll play!","I'll play. Calculation complete."],ganhou_mao:["As predicted.","One more point for the machine."],perdeu_mao:["Rounding error.","Recalibrating."],vitoria:["Game over. Good game, human."],derrota:["You win. Updating my data."]},usage:`retrucada: 1-on-1 truco in your terminal, played on the Retrucada server
|
|
10
|
+
|
|
11
|
+
npx retrucada opens the game
|
|
12
|
+
npx retrucada --en in English
|
|
13
|
+
npx retrucada --logout signs out on this computer
|
|
14
|
+
|
|
15
|
+
Esc hides the game at any time; q or Ctrl-C gives the terminal back as it was.
|
|
16
|
+
https://retrucada.com`},ht={pt:Ze,en:Xe},en="pt",a=()=>ht[en],Ce=()=>en,Re=e=>{en=e};var v=64,j=24,gt=["c","h","s","d"],Gn=e=>a().levels[e]??"";function zn(e,n,t){if(!e)return Pn();if(!e.card)return Qe();if(e.hidden)return Je(e.card,{faded:!0});let r=n.vira;return Je(e.card,{manilha:!e.plain&&gn(e.card,t,r)})}function bt(e){let{obs:n,hand:t}=e,r=n.me,o=M(r),i=[];for(let l=0;l<3;l++){let s=t.rounds[l],c=s?.result,m=c===void 0?"":c==="tie"?d(" \u2550\u2550\u2550"):c===r?xe(" \u25BC"):ne(" \u25B2");i.push([" "+d(a().round[l]),...zn(s?.cards[o],t,n.variant),m,...zn(s?.cards[r],t,n.variant)])}return P(i,3)}function vt(e){let n=e.hand;return e.obs.variant==="mineiro"?["","","",d(a().noVira)]:n.viraHidden?[d(a().vira),...Nn(),d(a().hiddenVira)]:n.vira?[" "+d(a().vira),...J(n.vira)]:[]}function yt(e){let{obs:n,hand:t}=e,r=[],o=_[n.variant][t.level];r.push(`${d(a().stake)} ${We(String(o))}${t.level?d(` \xB7 ${Gn(t.level)}`):""}`),t.pending?r.push(b(`${Gn(t.pending.level)}?`)):r.push(""),r.push(""),n.variant==="mineiro"?(r.push(d(a().manilhas)),r.push(Ge.slice().reverse().map(l=>Ye(l)).join(" "))):t.vira?(r.push(`${d(a().manilha)} ${Fe(we(t.vira))}`),r.push(gt.map(l=>Fe(Hn(l))).join(d(" \u203A ")))):r.push("",""),r.push("");let i=t.rounds[0]?.lead??M(n.dealer);return r.push(d(`${a().starts}: `)+(i===n.me?xe(a().you):ne(de(e.oppName,14)))),r}function _n(e,n,t,r){return`${k(r(de(e,16)),17)}${jn(n,t,r)} ${We(String(n))}`}function wt(e){if(e.banner)return["",...e.banner];let{obs:n}=e,t=n.myCards.map((r,o)=>{let i=e.picking&&o===e.selected,l=J(r.card,{manilha:!r.plain&&n.hand.manilhas.includes(r.card),faded:i&&e.cover});return i?[...l,e.cover?d(` ${a().covered}`):""]:["",...l]});return t.length?P(t,1):[]}function St(e){let n=e.map(([r,o])=>`${b(r)} ${d(o)}`),t=[];for(let r=0;r<n.length;r+=2)t.push(n[r+1]?k(n[r],17)+n[r+1]:n[r]);return t}function qn(e){let{obs:n}=e,t=n.me,r=M(t),o=[],i=`${b("retrucada")} ${d(`\xB7 ${a()[n.variant]}`)}`;o.push(" "+k(i,v-2-Y(e.right))+e.right),o.push("");let l=[_n(e.oppName,n.score[r],n.target,ne),e.speech?` ${b(`\u201C${de(e.speech,34)}\u201D`)}`:"",""],s=e.banner?[]:P(Array.from({length:e.hand===n.hand?n.hand.counts[r]:0},Qe),1);for(o.push(...P([l.map(S=>" "+S),s],2).map(S=>k(S,v)));o.length<5;)o.push("");o.push("");let c=P([re(vt(e),1).map(S=>" "+S),bt(e),re(yt(e),1)],4);for(let S=0;S<8;S++)o.push(c[S]??"");o.push(""),o.push(" "+_n(e.meName,n.score[t],n.target,xe));let m=[...e.status,"",...St(e.keys)],le=wt(e),et=P([le.map(S=>" "+S),m],4);for(let S=0;S<6;S++)o.push(et[S]??"");return o.push(""),o.push(" "+(e.error?q(de(e.error,v-2)):d(xt(e.log,v-2)))),o.slice(0,j)}var xt=(e,n)=>[...e].length<=n?e:"\u2026"+[...e].slice(-(n-1)).join("");function $t(e){let n=e.hand.manilhas.slice().reverse(),t=e.variant==="paulista"&&e.hand.vira?we(e.hand.vira):null,r=X.slice().reverse().filter(o=>o!==t);return{manilhas:n,ranks:r}}var nn=(e,n=t=>t)=>I(e,v-2).map(t=>" "+n(t));function In(e){let n=a().help,t=[" "+b(n.title),""];if(e&&e.hand.manilhas.length){let{manilhas:r,ranks:o}=$t(e);t.push(" "+d(n.now)),t.push(" "+r.map(Ye).join(d(" \u203A "))+d(` ${n.then} `)+o.join(d(" "))),t.push(...nn(n.suitNote,d)),t.push("")}e&&t.push(...nn(n.stakes(_[e.variant])));for(let r of n.lines)t.push(...nn(r));t.push("");for(let[r,o]of n.keys)t.push(" "+k(b(r),14)+d(o));return t.push(""),t.push(" "+d(n.close)),t.map(r=>k(r,v))}function an(){return[...P([re(J("4c",{manilha:!0}),1),J("7h",{manilha:!0}),re(J("As",{manilha:!0}),1)],1).map(n=>te(n,v)),te(b("r e t r u c a d a"),v),te(d(a().tagline),v)]}function Bn(e,n,t,r){let o=[...an(),""];for(e.forEach((i,l)=>{let s=l===n,c=s?b("\u25B8 "):" ",m=k(s?b(i.label):i.label,12),le=i.value===void 0?"":s?`${d("\u2039")} ${b(i.value)} ${d("\u203A")}`:` ${i.value} `;o.push(` ${c}${m}${i.value===void 0?"":k(le,22)}${i.desc?d(i.desc):""}`)}),o.push(""),o.push(" "+a().menuKeys.map(([i,l])=>`${b(i)} ${d(l)}`).join(" ")),r&&o.push(...I(r,on).map(i=>" "+q(i)));o.length<j-1;)o.push("");return o[j-1]=k("",v-Y(t)-1)+d(t),o}var on=v-12,tn=(e,n=!1)=>I(e,on).map(t=>" "+(n?d(t):t));function ue(e,n,t,r,o,i){let l=[...an(),""];for(let c of e)l.push(...tn(c));n&&l.push(...tn(n,!0)),l.push("");let s=g(" ",{bg:250});return l.push(` ${d(t.label)} ${b(t.value)}${i?"":s}`),l.push(""),o?l.push(...I(o,on).map(c=>" "+q(c))):l.push(...tn(i??r,!0)),l}function Te(e,n,t){let r=[...an(),"",""];r.push(te(`${b(t)} ${e}`,v)),r.push("");for(let o of n)r.push(te(d(o),v));return r}var kt=["src/utils/date.test.ts","src/utils/currency.test.ts","src/lib/retry.test.ts","src/lib/cache.test.ts","src/api/client.test.ts","src/api/pagination.test.ts","src/auth/session.test.ts","src/auth/permissions.test.ts","src/models/user.test.ts","src/models/invoice.test.ts","src/services/report.test.ts","src/services/export.test.ts","src/hooks/useDebounce.test.ts","src/components/Table.test.tsx","src/components/DatePicker.test.tsx","src/components/Modal.test.tsx"],rn=null;function Vn(){if(rn)return rn;let e=(c,m)=>c+Math.floor(Math.random()*(m-c+1)),n=c=>g(c,{fg:2}),t=c=>g(c,{fg:8}),r=kt.filter(()=>Math.random()<.8),o=0,i=["",` ${g(" RERUN ",{bg:4,fg:15})} ${t(r[e(0,r.length-1)])} ${t("x1")}`,""];for(let c of r){let m=e(2,24);o+=m,i.push(` ${n("\u2713")} ${c} ${t(`(${m} tests)`)} ${t(`${e(3,180)}ms`)}`)}let l=new Date,s=c=>String(c).padStart(2,"0");return i.push("",` ${t("Test Files")} ${n(`${r.length} passed`)} ${t(`(${r.length})`)}`,` ${t("Tests")} ${n(`${o} passed`)} ${t(`(${o})`)}`,` ${t("Start at")} ${s(l.getHours())}:${s(l.getMinutes())}:${s(l.getSeconds())}`,` ${t("Duration")} ${(e(900,3200)/1e3).toFixed(2)}s ${t(`(transform ${e(200,600)}ms, tests ${e(300,1200)}ms)`)}`,"",` ${g(" PASS ",{bg:2,fg:0})} ${n("Waiting for file changes...")}`,` ${t("press")} h ${t("to show help,")} ${t("press")} q ${t("to quit")}`),rn=i}var Ct={"\x1B[A":"up","\x1B[B":"down","\x1B[C":"right","\x1B[D":"left","\x1BOA":"up","\x1BOB":"down","\x1BOC":"right","\x1BOD":"left","\r":"enter","\n":"enter","\x1B":"esc","\x7F":"backspace","\b":"backspace"," ":"tab","":"ctrl-c"};function Rt(e){let n=Ct[e];if(n)return[{k:n}];if(e.startsWith("\x1B"))return[];if([...e].length>1){let t=e.replace(/[\r\n]+$/,""),r=t.includes("")?[{k:"ctrl-c"}]:[{k:"text",text:t.replace(/[\x00-\x1f\x7f]/g,"")}];return t!==e&&r.push({k:"enter"}),r}return[{k:"char",ch:e}]}var ae=process.stdout,sn=!1,ln=()=>({w:ae.columns||80,h:ae.rows||24});function Dn(e,n){sn=!0,ae.write("\x1B[?1049h\x1B[?25l\x1B[H\x1B[2J"),process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdin.on("data",t=>Rt(t).forEach(e)),ae.on("resize",n)}function fe(){sn&&(sn=!1,ae.write("\x1B[0m\x1B[?25h\x1B[?1049l"),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause())}function Ae(e,n){let{w:t,h:r}=ln(),o=n.corner?0:Math.max(0,Math.floor((r-n.h)/2)),i=n.corner?0:Math.max(0,Math.floor((t-n.w)/2)),l=" ".repeat(i),s=[];for(let c=0;c<r;c++){let m=c-o>=0?e[c-o]:void 0;s.push(m===void 0?"":l+m)}ae.write("\x1B[H"+s.map(c=>c+"\x1B[0m\x1B[K").join(`\r
|
|
17
|
+
`))}var un=(()=>{try{return JSON.parse(Tt(new URL("../package.json",import.meta.url),"utf8")).version}catch{return"0.0.0"}})(),D=process.argv.slice(2);(D.includes("--help")||D.includes("-h"))&&(console.log(`retrucada ${un}
|
|
18
|
+
`),Re(D.includes("--en")?"en":"pt"),console.log(a().usage),process.exit(0));(D.includes("--version")||D.includes("-v"))&&(console.log(un),process.exit(0));var R=kn();An(un);Re(D.includes("--en")?"en":D.includes("--pt")?"pt":R.lang??"pt");De(R.theme??"discreto");En(!process.env.NO_COLOR);ce(R.session??null);D.includes("--logout")&&(R.session&&await y.logout().catch(()=>{}),Rn(),process.exit(0));(!process.stdin.isTTY||!process.stdout.isTTY)&&(console.error(a().usage),process.exit(1));var Un=[...Sn.map(e=>`robot:${e}`),"human","friend","join"],Q=R.variant??"paulista",L=Un.includes(R.opp??"")?R.opp:"robot:medium",Ee=R.theme??"discreto",Pe=()=>Cn({...R,lang:Ce(),theme:Ee,variant:Q,opp:L}),f={m:"boot",offline:!1},p="",$=null,C=!1,H=null,W=null,me=!1,he=!1,K=!1,cn=0,u=null,He=0,Le=0,be=null,G=!1,O=0,Z=!1,fn="",ie=null,dn=!1,F=null,x=null,Ne=null,B=0,E={w:0,l:0},Wn="",pn=e=>new Promise(n=>setTimeout(n,e)),V=e=>e instanceof N?a().apiErrors[e.message]??e.message:a().offline,Kn="\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F",ge=()=>Kn[cn%Kn.length];function se(e){let n=e?.opponent;return n?n.type==="robot"?a().robot(n.level):n.type==="human"?n.username:n.model:"\u2026"}var ve=()=>u?.opponent?.type==="robot";function w(){if(me)return Ae(Vn(),{w:v,h:j,corner:!0});let{w:e,h:n}=ln();if(e<v||n<j)return Ae(I(a().tooSmall(e,n,[v,j]),e-1),{w:e,h:n,corner:!0});Ae(At(),{w:v,h:j})}function At(){switch(f.m){case"boot":return Te(f.offline?a().offline:"",[],ge());case"email":return ue([a().loginIntro],a().loginWhy,{label:a().email,value:p},"",$,C?a().sending:null);case"code":return ue([a().codeSent(f.email)],null,{label:a().code,value:p},a().codeBack,$,C?a().sending:null);case"username":return ue([a().usernameIntro],null,{label:a().username,value:p},"",$,C?a().sending:null);case"join":return ue([a().joinIntro],null,{label:a().joinCode,value:p},"",$,C?a().sending:null);case"menu":{let e=Yn(),n=[H?`@${H}`:"",E.w+E.l?a().sessionScore(E.w,E.l):""].filter(Boolean).join(" \xB7 ");return Bn(e,f.sel,n,$)}case"waiting":return u?.friend_code?Te(a().friendCode(u.friend_code),[a().friendHint,"",a().friendWait],ge()):Te(u?a().queue:"",u?[a().queueHint]:[],ge());case"game":return he?In(u?.observation??null):_t()}}function Ot(e){return e.startsWith("robot:")?a().robot(e.slice(6)):e==="human"?a().human:e==="friend"?a().friendNew:a().friendJoin}function Yn(){let e=[];if(W?.observation){let n=W.observation;e.push({id:"resume",label:a().resume,desc:a().resumeDesc(se(W),`${n.score[n.me]} \xD7 ${n.score[M(n.me)]}`)})}return e.push({id:"variant",label:a().style,value:a()[Q],desc:Q==="paulista"?a().paulistaDesc:a().mineiroDesc},{id:"opp",label:a().opponent,value:Ot(L),desc:L.startsWith("robot:")?a().rated:L==="human"?a().queueDesc:a().unrated},{id:"theme",label:a().colors,value:a().themes[Ee]},{id:"lang",label:a().language,value:a().langName},{id:"play",label:a().play},{id:"logout",label:a().logout}),e}var Oe=(e,n,t)=>e[(e.indexOf(n)+t+e.length)%e.length];function Mt(e){if(f.m!=="menu")return;let n=Yn(),t=n[f.sel];if($=null,e.k==="up")f.sel=(f.sel+n.length-1)%n.length;else if(e.k==="down"||e.k==="tab")f.sel=(f.sel+1)%n.length;else if(e.k==="left"||e.k==="right"){let r=e.k==="left"?-1:1;t.id==="variant"&&(Q=Oe(["paulista","mineiro"],Q,r)),t.id==="opp"&&(L=Oe(Un,L,r)),t.id==="theme"&&De(Ee=Oe(On,Ee,r)),t.id==="lang"&&Re(Oe(["pt","en"],Ce(),r)),Pe()}else e.k==="enter"||e.k==="char"&&e.ch===" "?t.id==="resume"&&W?Nt(W):t.id==="logout"?Lt():Jn():e.k==="char"&&e.ch==="q"&&ye()}async function Lt(){await y.logout().catch(()=>{}),R.session=void 0,ce(null),H=null,W=null,Pe(),p="",f={m:"email"}}function Me(e,n,t){let r=o=>p=(p+[...o].filter(i=>n.test(i)).join("")).slice(0,t);if(e.k==="char")r(e.ch);else if(e.k==="text")r(e.text);else if(e.k==="backspace")p=p.slice(0,-1);else return!1;return $=null,!0}async function Et(e){if(!C){if(f.m==="email"){if(Me(e,/[^\s]/,120)||e.k!=="enter"||!p)return;C=!0;try{let n=await y.loginStart(p.trim(),Ce());f={m:"code",email:n.email,...n.devCode?{dev:n.devCode}:{}},p=n.devCode??""}catch(n){$=V(n)}C=!1}else if(f.m==="code"){if(e.k==="backspace"&&!p){p="",f={m:"email"};return}if(Me(e,/\d/,6),p.length<6||e.k!=="enter"&&e.k!=="char"&&e.k!=="text")return;C=!0,w();try{let n=await y.loginVerify(f.email,p);R.session=n.session,ce(n.session),Pe(),H=n.username,p="",H?await z():f={m:"username"}}catch(n){$=V(n),p=""}C=!1}else if(f.m==="username"){if(Me(e,/[A-Za-z0-9_]/,16)||e.k!=="enter"||!p)return;C=!0;try{H=(await y.setUsername(p)).username,p="",await z()}catch(n){$=V(n)}C=!1}else if(f.m==="join"){if(e.k==="char"&&e.ch==="q"&&!p)return void z();if(Me(e,/[A-Za-z0-9]/,12))return void(p=p.toUpperCase());if(e.k!=="enter"||!p)return;C=!0;try{let n=await y.newGame({variant:Q,opponent:"friend",join_code:p});p="",mn(n,!0)}catch(n){$=V(n)}C=!1}}}async function z(){B++,u=null,$=null,W=null,f={m:"menu",sel:0};try{let{games:e}=await y.myGames(),n=e.find(t=>t.mode==="table"&&t.status==="playing");n&&(W=await y.game(n.game_id))}catch{}f.m==="menu"&&(f.sel=0)}async function Ht(){for(;;)try{if(!R.session){f={m:"email"};return}H=(await y.me()).username,H?await z():f={m:"username"};return}catch(e){if(e instanceof N&&e.status===401){R.session=void 0,ce(null),Pe(),f={m:"email"};return}f={m:"boot",offline:!0},w(),await pn(3e3)}}async function Jn(){$=null;let e={variant:Q};if(L.startsWith("robot:"))Object.assign(e,{opponent:"robot",level:L.slice(6)});else if(L==="human")e.opponent="human";else if(L==="friend")e.opponent="friend";else{p="",f={m:"join"};return}f={m:"waiting"},u=null,w();try{mn(await y.newGame(e),!0)}catch(n){if(n instanceof N&&n.message==="need-username"){p="",f={m:"username"};return}await z(),$=V(n)}}async function Nt(e){mn(await y.game(e.game_id).catch(()=>e),!1)}function mn(e,n){B++,u=e;let t=e.observation;He=n||!t?0:t.events.length,Le=t?.results.length??0,be=null,G=!1,O=0,Z=!1,fn="",ie=null,F=null,x=null,K=!1,he=!1,f=e.status==="waiting"?{m:"waiting"}:{m:"game"},t&&je(e),Zn()}function oe(e){let n=a().speech[e];if(!n?.length)return;F={text:ve()?n[Math.floor(Math.random()*n.length)]:n[0],until:Date.now()+5e3}}var Pt=["","truco","seis","nove","doze"];function jt(e,n){let t=n.side===e.me,r=t?a().you:se(u),o=a().ev;switch(n.t){case"play":return n.hidden?t&&n.card?o.coveredMine(_e(n.card)):o.coveredOpp(r):n.card?o.played(r,_e(n.card)):"";case"raise":return o.raised(r,a().levels[n.level??1]);case"accept":return o.accepted(r);case"fold":return o.folded(r);case"playHand":return o.playHand(r);case"resign":return o.resigned(r);default:return""}}function je(e){let n=u?.observation&&u.observation!==e.observation?u.observation:null;u=e,be=null,Ne=e.seconds_left_to_move!=null&&e.your_turn?Date.now()+e.seconds_left_to_move*1e3:null;let t=e.observation;if(!t)return;let r=[];for(let s of t.events.slice(He)){let c=jt(t,s);c&&r.push(c),s.side!==t.me&&(s.t==="raise"?oe(Pt[s.level??1]):s.t==="accept"?oe("quero"):s.t==="fold"?oe("corro"):s.t==="playHand"&&oe("jogo"))}let o=n?.hand,i=n&&n.handNo===t.handNo?t.hand:t.lastHand;o&&i&&i.rounds.forEach((s,c)=>{s.result===void 0||o.rounds[c]?.result!==void 0||r.push(s.result==="tie"?a().ev.roundTie(c):a().ev.roundWon(s.result===t.me?a().you:se(u),c))}),r.length&&(fn=r.join(" \xB7 ")),He=t.events.length;let l=e.status==="over";if(t.results.length>Le||l){let s=t.results[t.results.length-1],c=[];if(s&&t.results.length>Le){let m=se(u);s.winner===null?c.push(d(a().handNone)):c.push((s.winner===t.me?Ke(a().handWon(s.points)):ne(a().handLost(m,s.points)))+(s.why==="fold"?" "+d(a().handFold(s.winner===t.me?m:a().you)):"")),!l&&ve()&&Math.random()<.5&&oe(s.winner===t.me?"perdeu_mao":s.winner===null?"":"ganhou_mao")}if(l){let m=e.winner==="you";c.push("",(m?Ke(a().youWon):q(a().youLost))+d(` ${t.score[t.me]} \xD7 ${t.score[M(t.me)]}`)),e.reason==="resign"&&c.push(d(a().byResign(m?se(u):a().you))),e.reason==="away"&&c.push(d(a().byAway(!m))),e.rating&&c.push(d(a().rating(a()[t.variant],e.rating.before,e.rating.after))),Wn!==e.game_id&&(Wn=e.game_id,m?E.w++:E.l++,ve()&&oe(m?"derrota":"vitoria"))}x={hand:t.lastHand??t.hand,banner:c,until:l?null:Date.now()+4e3}}Le=t.results.length,O=Math.min(O,Math.max(0,t.myCards.length-1))}var Qn=e=>!!e?.observation&&e.observation.actor===e.observation.me;async function Zn(){let e=++B;for(;e===B&&u&&(u.status==="waiting"||u.status==="playing"&&!Qn(u));){try{let n=await y.wait(u.game_id,u.observation?u.observation.events.length:-1);if(e!==B)return;if(dn=!1,n.status==="cancelled")return await z(),$=a().cancelled,w();f.m==="waiting"&&n.status!=="waiting"&&(f={m:"game"},He=0),je(n)}catch(n){if(e!==B)return;dn=!(n instanceof N),n instanceof N&&(ie=V(n)),w(),await pn(2e3)}w()}}function Gt(e,n){let t=structuredClone(e),r=t.me;if(t.actor=M(r),t.legal=[],n.t==="play"){let o=t.myCards.findIndex(s=>s.i===n.card),[i]=t.myCards.splice(o,1),l=t.hand.rounds[t.hand.rounds.length-1];(!l||l.result!==void 0)&&t.hand.rounds.push(l={lead:r,cards:[null,null]}),l.cards[r]={card:i.card,i:i.i,hidden:!!n.hidden}}else n.t==="raise"?t.hand.pending={by:r,level:(t.hand.pending?.level??t.hand.level)+1}:n.t==="accept"&&t.hand.pending&&(t.hand.level=t.hand.pending.level,t.hand.pending=null);return t}async function pe(e){if(!e||G||!u?.observation)return;let n=u.observation;G=!0,ie=null,Z=!1,be=Gt(n,e),e.t==="play"&&(O=0);let t=Date.now();w();try{let r=await y.move(u.game_id,yn(n,e)),o=(r.observation?.events.length??0)>n.events.length+1;ve()&&o&&await pn(Math.max(0,600+Math.random()*400-(Date.now()-t))),je(r)}catch(r){ie=V(r),be=null,u=await y.game(u.game_id).catch(()=>u)}G=!1,w(),Zn()}async function zt(){if(K=!1,!!u){B++;try{je(await y.resign(u.game_id))}catch(e){ie=V(e)}}}function Xn(e){let n=r=>e.legal.find(o=>o.t===r),t=r=>e.legal.filter(o=>o.t==="play"&&!!o.hidden===r);return{raise:n("raise"),accept:n("accept"),fold:n("fold"),playHand:n("playHand"),open:t(!1),covered:t(!0)}}function _t(){let e=u.observation,n=be??e,t=Xn(n),r=se(u),o=!G&&!x&&t.open.length>0,i=[],l=[],s=a().keys,c=(n.hand.pending?.level??n.hand.level)+1;if(K)i.push(q(a().confirmResign),d(a().yesNo));else if(x)u.status==="over"?l.push(["\u23CE",s.again],["m",s.menu],["q",s.quit]):l.push(["\u23CE",s.next]);else if(G)i.push(`${b(ge())} ${d(ve()?a().thinking(r):a().waitingFor(r))}`);else if(n.actor===n.me){let m=n.target-_[n.variant][0];t.playHand?(i.push(b(a().onze(m))),l.push(["j",s.playHand],["r",s.fold])):n.hand.pending&&n.hand.pending.by!==n.me?(i.push(b(a().asked(r,a().levels[n.hand.pending.level]))),l.push(["a",s.accept],["r",s.fold]),t.raise&&l.push(["t",a().levels[c]])):(i.push(b(n.hand.rounds.every(le=>!le.cards[n.me])&&n.myCards.length===3?a().firstLook:a().yourTurn)),l.push(["\u2190\u2192",s.pick],["\u23CE",s.play]),t.raise&&l.push(["t",a().levels[c]]),t.covered.length&&l.push(["c",Z?s.coverOn:s.cover])),Ne&&i.push(d(a().secondsLeft(Math.max(0,Math.ceil((Ne-Date.now())/1e3)))))}else if(u.status==="playing"){let m=n.hand.pending?.by===n.me?a().waitingAnswer(r):n.hand.phase==="onze"?a().onzeOpp(r,n.target-_[n.variant][0]):a().waitingFor(r);i.push(`${b(ge())} ${d(m)}`)}return!x&&!K&&l.push(["?",s.help],["esc",s.hide]),!x&&!K&&u.status==="playing"&&l.push(["q",s.quit]),qn({obs:n,hand:x?.hand??n.hand,banner:x?x.banner:null,oppName:r,meName:a().you,right:d([H?`@${H}`:"",E.w+E.l?a().sessionScore(E.w,E.l):""].filter(Boolean).join(" \xB7 ")),selected:O,picking:o,cover:Z,speech:F&&F.until>Date.now()?F.text:null,status:i,keys:l,log:dn?a().offline:fn,error:ie})}function Fn(e=O){let n=u?.observation;if(!n||G||x)return;let t=n.myCards[e];if(!t)return;let r=n.legal.find(o=>o.t==="play"&&o.card===t.i&&!!o.hidden===Z);r&&pe(r)}function qt(e){let n=u?.observation;if(!n||!u)return;if(he)return void(he=!1);if(K){e.k==="char"&&(e.ch===a().yes||e.ch==="s"||e.ch==="y")?zt():K=!1;return}if(x){if(u.status==="over"){e.k==="enter"||e.k==="char"&&e.ch===" "?Jn():e.k==="char"&&e.ch==="m"?z():e.k==="char"&&e.ch==="q"&&ye();return}x=null;return}if(e.k==="char"&&e.ch==="?")return void(he=!0);if(e.k==="char"&&e.ch==="q"){u.status==="playing"?K=!0:z();return}if(G||n.actor!==n.me)return;let t=Xn(n),r=n.myCards.length;if(e.k==="left"||e.k==="char"&&e.ch==="h")O=(O+r-1)%Math.max(1,r);else if(e.k==="right"||e.k==="char"&&e.ch==="l")O=(O+1)%Math.max(1,r);else if(e.k==="enter"||e.k==="char"&&e.ch===" ")Fn();else if(e.k==="char"&&/^[1-3]$/.test(e.ch))O=Number(e.ch)-1,Fn();else if(e.k==="char"){let o=e.ch.toLowerCase();o==="c"&&t.covered.length?Z=!Z:o==="t"?pe(t.raise):o==="a"?pe(t.accept):o==="r"?pe(t.fold):o==="j"&&pe(t.playHand)}}function It(e){if(e.k==="char"&&e.ch==="q"){let n=u;B++,n&&y.resign(n.game_id).catch(()=>{}),z().then(w)}}function ye(e=0){fe(),process.exit(e)}async function Bt(e){if(e.k==="ctrl-c")return ye();if(me)return me=!1,w();if(e.k==="esc")return me=!0,w();switch(f.m){case"menu":Mt(e);break;case"game":qt(e);break;case"waiting":It(e);break;case"boot":e.k==="char"&&e.ch==="q"&&ye();break;default:w(),await Et(e)}w()}process.on("uncaughtException",e=>{fe(),console.error(e),process.exit(1)});process.on("unhandledRejection",e=>{fe(),console.error(e),process.exit(1)});process.on("SIGTERM",()=>ye());process.on("exit",fe);Dn(e=>{Bt(e)},w);setInterval(()=>{if(cn++,me)return;x?.until&&x.until<Date.now()&&(x=null),F&&F.until<Date.now()&&(F=null),(f.m==="boot"||f.m==="waiting"||f.m==="game"&&(G||!Qn(u)||Ne!==null)||cn%8===0)&&w()},120);w();await Ht();w();
|
package/package.json
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "retrucada",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Truco 1×1 no terminal, jogando no servidor da Retrucada (paulista e mineiro)",
|
|
5
|
+
"keywords": ["truco", "game", "terminal", "tui", "cli"],
|
|
6
|
+
"homepage": "https://retrucada.com",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"bin": { "retrucada": "dist/retrucada.js" },
|
|
10
|
+
"files": ["dist"],
|
|
11
|
+
"engines": { "node": ">=20" },
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "esbuild src/main.ts --bundle --minify --platform=node --format=esm --target=node20 --outfile=dist/retrucada.js --banner:js='#!/usr/bin/env node'",
|
|
14
|
+
"typecheck": "tsc -p .",
|
|
15
|
+
"prepublishOnly": "pnpm build"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"esbuild": "^0.28.2"
|
|
19
|
+
}
|
|
20
|
+
}
|