diff --git a/plugins/damas/.idea/.gitignore b/plugins/damas/.idea/.gitignore deleted file mode 100644 index 30cf57e..0000000 --- a/plugins/damas/.idea/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Ignored default folder with query files -/queries/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/plugins/damas/.idea/libraries/pitiupi_damas.xml b/plugins/damas/.idea/libraries/pitiupi_damas.xml deleted file mode 100644 index e8813d0..0000000 --- a/plugins/damas/.idea/libraries/pitiupi_damas.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/plugins/damas/.idea/misc.xml b/plugins/damas/.idea/misc.xml deleted file mode 100644 index 3653b1f..0000000 --- a/plugins/damas/.idea/misc.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/plugins/damas/.idea/modules.xml b/plugins/damas/.idea/modules.xml deleted file mode 100644 index a863e08..0000000 --- a/plugins/damas/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/plugins/damas/.idea/vcs.xml b/plugins/damas/.idea/vcs.xml deleted file mode 100644 index b2bdec2..0000000 --- a/plugins/damas/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/plugins/damas/README.md b/plugins/damas/README.md deleted file mode 100644 index b72d89e..0000000 --- a/plugins/damas/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# Plugin Damas - -Jogo de damas para dois peers da mesma sala, com regras brasileiras. Não exige nenhuma mudança no núcleo. - -## Como jogar - -1. Abra **Damas** na aba **Plugins**, escolha um adversário e clique em **Convidar**. Outra opção é clicar no nome do peer na lista lateral e usar **Damas → Convidar para uma partida**. -2. O convidado vê o convite na aba do plugin, que abre sozinha, e clica em **Aceitar** ou **Recusar**. Os lados são sorteados. -3. Na sua vez, as peças que podem jogar ficam contornadas em verde. Clique na peça e depois em cada casa de pouso, uma por vez nas capturas em sequência. Para refazer a escolha no meio de uma sequência, clique em qualquer outra casa. - -Fechar a aba não encerra a partida: ela continua em andamento e a barra de status avisa quando for a sua vez. Para voltar, abra **Damas** de novo. - -Os dois peers precisam ter a **mesma versão do JAR** e usar a **mesma porta** no login, inclusive no mesmo computador. Com portas diferentes, as instâncias não se enxergam. - -## Regras - -- Tabuleiro 8×8, 12 peças para cada lado, e as brancas começam. -- Pedras andam uma casa para a frente e capturam para a frente e para trás. -- Damas são voadoras: andam e capturam a qualquer distância na diagonal. -- A captura é obrigatória, e a lei da maioria exige a sequência com mais peças. Em caso de igualdade, a escolha é livre. -- Peças capturadas só saem no fim da sequência e não podem ser saltadas duas vezes. -- Pedra que passa pela última linha no meio de uma captura só vira dama se terminar nela. -- Perde quem fica sem peças ou sem lances. -- Empate após 20 lances de cada lado só com damas, sem captura nem movimento de pedra. - -## Protocolo - -**Teoria:** UDP não garante entrega nem ordem. Para ter confiabilidade sobre ele, a aplicação precisa confirmar o recebimento (ACK), retransmitir o que não foi confirmado e ignorar duplicatas. - -**No Pitiupi:** toda comunicação é uma única `DamasMessage`, enviada por UDP multicast com `to` indicando o destinatário. O multicast foi escolhido porque é o caminho do heartbeat: se o peer aparece na lista, o canal funciona. TCP e unicast usam a porta local como destino e não alcançam outra instância no mesmo computador. - -| Tipo | Quando | -| --- | --- | -| `INVITE` | Convite, com o lado sorteado de quem convida | -| `ACCEPT`, `DECLINE`, `CANCEL` | Resposta ao convite ou cancelamento | -| `BUSY` | Resposta automática de quem já está em partida ou com convite aberto | -| `MOVE` | Caminho completo do lance | -| `RESIGN` | Desistência ou encerramento | -| `ACK` | Confirmação de `gameId` + `seq` | - -`DamasController` reenvia a cada 500 ms o que não foi confirmado e processa cada mensagem uma única vez. O convite é abandonado após 10 s sem ACK. O lance da partida em curso é reenviado até ser confirmado, porque o adversário pode voltar à rede. Cada peer valida o lance recebido com o próprio `DamasGame`. - -**Limitação:** não há criptografia nem autenticação, e qualquer peer da sala pode ler as mensagens. As partidas não são salvas em disco e não existe proposta de empate. A regra oficial de empate em finais como duas damas contra uma não foi implementada. - -## Build e testes - -```bash -cd plugins/damas -ant jar # requer pitiupi/dist/pitiupi.jar -ant test # requer o JUnit em pitiupi/test/lib (ver README da pasta) -``` - -| Pacote | Conteúdo | -| --- | --- | -| `game` | Regras, sem rede nem Swing | -| `net` | `DamasMessage` | -| `control` | Sessão, convites e entrega confiável | -| `GUI` | Tabuleiro e painel | -| `plugin` | Integração com o núcleo (`DamasPlugin`) | diff --git a/plugins/damas/build.xml b/plugins/damas/build.xml deleted file mode 100644 index 3a7e2bc..0000000 --- a/plugins/damas/build.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - Builds, tests, and runs the project pitiupi.damas. - - - - - - - - - - - - - - - - - - diff --git a/plugins/damas/build/built-jar.properties b/plugins/damas/build/built-jar.properties deleted file mode 100644 index f00ca39..0000000 --- a/plugins/damas/build/built-jar.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Wed, 04 Nov 2026 10:51:29 -0300 - - -C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\dama\\pitiupi\\plugins\\damas= - -C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\dama\\pitiupi\\pitiupi= diff --git a/plugins/damas/build/classes/META-INF/services/pitiupi.models.Plugin b/plugins/damas/build/classes/META-INF/services/pitiupi.models.Plugin deleted file mode 100644 index 51af5e8..0000000 --- a/plugins/damas/build/classes/META-INF/services/pitiupi.models.Plugin +++ /dev/null @@ -1 +0,0 @@ -pitiupi.damas.plugin.DamasPlugin diff --git a/plugins/damas/build/classes/pitiupi/damas/GUI/BoardView$1.class b/plugins/damas/build/classes/pitiupi/damas/GUI/BoardView$1.class deleted file mode 100644 index 1af6adc..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/GUI/BoardView$1.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/GUI/BoardView.class b/plugins/damas/build/classes/pitiupi/damas/GUI/BoardView.class deleted file mode 100644 index 3e692e3..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/GUI/BoardView.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$1.class b/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$1.class deleted file mode 100644 index 421622b..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$1.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$2.class b/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$2.class deleted file mode 100644 index 62a85e2..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$2.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$PeerItem.class b/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$PeerItem.class deleted file mode 100644 index 12968a4..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel$PeerItem.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel.class b/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel.class deleted file mode 100644 index fc98206..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/GUI/DamasPanel.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$1.class b/plugins/damas/build/classes/pitiupi/damas/control/DamasController$1.class deleted file mode 100644 index e7d9fe7..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$1.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$IncomingInvite.class b/plugins/damas/build/classes/pitiupi/damas/control/DamasController$IncomingInvite.class deleted file mode 100644 index 7c4fbc8..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$IncomingInvite.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Listener.class b/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Listener.class deleted file mode 100644 index 5a60a05..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Listener.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Pending.class b/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Pending.class deleted file mode 100644 index 357826c..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Pending.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Phase.class b/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Phase.class deleted file mode 100644 index 510f808..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/control/DamasController$Phase.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/control/DamasController.class b/plugins/damas/build/classes/pitiupi/damas/control/DamasController.class deleted file mode 100644 index fcc8ebf..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/control/DamasController.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/game/DamasGame.class b/plugins/damas/build/classes/pitiupi/damas/game/DamasGame.class deleted file mode 100644 index c79e215..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/game/DamasGame.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/game/GameResult.class b/plugins/damas/build/classes/pitiupi/damas/game/GameResult.class deleted file mode 100644 index fff1ce2..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/game/GameResult.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/game/Move.class b/plugins/damas/build/classes/pitiupi/damas/game/Move.class deleted file mode 100644 index 0b15f08..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/game/Move.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/game/Piece.class b/plugins/damas/build/classes/pitiupi/damas/game/Piece.class deleted file mode 100644 index afebde9..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/game/Piece.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/game/Side.class b/plugins/damas/build/classes/pitiupi/damas/game/Side.class deleted file mode 100644 index 6993efb..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/game/Side.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/net/DamasMessage$Type.class b/plugins/damas/build/classes/pitiupi/damas/net/DamasMessage$Type.class deleted file mode 100644 index d505ff0..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/net/DamasMessage$Type.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/net/DamasMessage.class b/plugins/damas/build/classes/pitiupi/damas/net/DamasMessage.class deleted file mode 100644 index 603005c..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/net/DamasMessage.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin$1.class b/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin$1.class deleted file mode 100644 index 726848a..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin$1.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin$2.class b/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin$2.class deleted file mode 100644 index 86e2123..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin$2.class and /dev/null differ diff --git a/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin.class b/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin.class deleted file mode 100644 index a649de6..0000000 Binary files a/plugins/damas/build/classes/pitiupi/damas/plugin/DamasPlugin.class and /dev/null differ diff --git a/plugins/damas/damas.iml b/plugins/damas/damas.iml deleted file mode 100644 index 8d24403..0000000 --- a/plugins/damas/damas.iml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/plugins/damas/dist/pitiupi.damas.jar b/plugins/damas/dist/pitiupi.damas.jar deleted file mode 100644 index edb35d5..0000000 Binary files a/plugins/damas/dist/pitiupi.damas.jar and /dev/null differ diff --git a/plugins/damas/nbproject/build-impl.xml b/plugins/damas/nbproject/build-impl.xml deleted file mode 100644 index 39fe9ea..0000000 --- a/plugins/damas/nbproject/build-impl.xml +++ /dev/null @@ -1,1789 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set src.dir - Must set test.src.dir - Must set build.dir - Must set dist.dir - Must set build.classes.dir - Must set dist.javadoc.dir - Must set build.test.classes.dir - Must set build.test.results.dir - Must set build.classes.excludes - Must set dist.jar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - No tests executed. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must set JVM to use for profiling in profiler.info.jvm - Must set profiler agent JVM arguments in profiler.info.jvmargs.agent - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - To run this application from the command line without Ant, try: - - java -jar "${dist.jar.resolved}" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set run.class - - - - Must select one file in the IDE or set run.class - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set debug.class - - - - - Must select one file in the IDE or set debug.class - - - - - Must set fix.includes - - - - - - - - - - This target only works when run from inside the NetBeans IDE. - - - - - - - - - Must select one file in the IDE or set profile.class - This target only works when run from inside the NetBeans IDE. - - - - - - - - - This target only works when run from inside the NetBeans IDE. - - - - - - - - - - - - - This target only works when run from inside the NetBeans IDE. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select one file in the IDE or set run.class - - - - - - Must select some files in the IDE or set test.includes - - - - - Must select one file in the IDE or set run.class - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Must select some files in the IDE or set javac.includes - - - - - - - - - - - - - - - - - - - - - - - - Some tests failed; see details above. - - - - - - - - - Must select some files in the IDE or set test.includes - - - - Some tests failed; see details above. - - - - Must select some files in the IDE or set test.class - Must select some method in the IDE or set test.method - - - - Some tests failed; see details above. - - - - - Must select one file in the IDE or set test.class - - - - Must select one file in the IDE or set test.class - Must select some method in the IDE or set test.method - - - - - - - - - - - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - Must select one file in the IDE or set applet.url - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/damas/nbproject/genfiles.properties b/plugins/damas/nbproject/genfiles.properties deleted file mode 100644 index 42ba841..0000000 --- a/plugins/damas/nbproject/genfiles.properties +++ /dev/null @@ -1,8 +0,0 @@ -build.xml.data.CRC32=3f66efc2 -build.xml.script.CRC32=3953f1a4 -build.xml.stylesheet.CRC32=f85dc8f2@1.119.0.48 -# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. -# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=3f66efc2 -nbproject/build-impl.xml.script.CRC32=a4594806 -nbproject/build-impl.xml.stylesheet.CRC32=12e0a6c2@1.119.0.48 diff --git a/plugins/damas/nbproject/project.properties b/plugins/damas/nbproject/project.properties deleted file mode 100644 index c4bbcd8..0000000 --- a/plugins/damas/nbproject/project.properties +++ /dev/null @@ -1,98 +0,0 @@ -annotation.processing.enabled=true -annotation.processing.enabled.in.editor=false -annotation.processing.processors.list= -annotation.processing.run.all.processors=true -annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output -application.title=pitiupi.damas -application.vendor=pitiupi -build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form -# This directory is removed when the project is cleaned: -build.dir=build -build.generated.dir=${build.dir}/generated -build.generated.sources.dir=${build.dir}/generated-sources -# Only compile against the classpath explicitly listed here: -build.sysclasspath=ignore -build.test.classes.dir=${build.dir}/test/classes -build.test.results.dir=${build.dir}/test/results -# Uncomment to specify the preferred debugger connection transport: -#debug.transport=dt_socket -debug.classpath=\ - ${run.classpath} -debug.modulepath=\ - ${run.modulepath} -debug.test.classpath=\ - ${run.test.classpath} -debug.test.modulepath=\ - ${run.test.modulepath} -# Files in build.classes.dir which should be excluded from distribution jar -dist.archive.excludes= -# This directory is removed when the project is cleaned: -dist.dir=dist -dist.jar=${dist.dir}/pitiupi.damas.jar -dist.javadoc.dir=${dist.dir}/javadoc -dist.jlink.dir=${dist.dir}/jlink -dist.jlink.output=${dist.jlink.dir}/pitiupi.damas -endorsed.classpath= -excludes= -includes=** -jar.compress=false -javac.classpath=\ - ${reference.pitiupi.jar} -# Space-separated list of extra javac options -javac.compilerargs= -javac.deprecation=false -javac.external.vm=true -javac.modulepath= -javac.processormodulepath= -javac.processorpath=\ - ${javac.classpath} -javac.source=17 -javac.target=17 -javac.test.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -javac.test.modulepath=\ - ${javac.modulepath} -javac.test.processorpath=\ - ${javac.test.classpath} -javadoc.additionalparam= -javadoc.author=false -javadoc.encoding=${source.encoding} -javadoc.html5=false -javadoc.noindex=false -javadoc.nonavbar=false -javadoc.notree=false -javadoc.private=false -javadoc.splitindex=true -javadoc.use=true -javadoc.version=false -javadoc.windowtitle= -# The jlink additional root modules to resolve -jlink.additionalmodules= -# The jlink additional command line parameters -jlink.additionalparam= -jlink.launcher=true -jlink.launcher.name=pitiupi.damas -meta.inf.dir=${src.dir}/META-INF -mkdist.disabled=true -platform.active=default_platform -project.pitiupi=../../pitiupi -reference.pitiupi.jar=${project.pitiupi}/dist/pitiupi.jar -run.classpath=\ - ${javac.classpath}:\ - ${build.classes.dir} -# Space-separated list of JVM arguments used when running the project. -# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. -# To set system properties for unit tests define test-sys-prop.name=value: -run.jvmargs= -run.modulepath=\ - ${javac.modulepath} -run.test.classpath=\ - ${javac.test.classpath}:\ - ${build.test.classes.dir} -run.test.modulepath=\ - ${javac.test.modulepath} -source.encoding=UTF-8 -src.dir=src -test.src.dir=test diff --git a/plugins/damas/nbproject/project.xml b/plugins/damas/nbproject/project.xml deleted file mode 100644 index f31e3b1..0000000 --- a/plugins/damas/nbproject/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - org.netbeans.modules.java.j2seproject - - - pitiupi.damas - - - - - - - - - - pitiupi - jar - - jar - clean - jar - - - - diff --git a/plugins/damas/src/META-INF/services/pitiupi.models.Plugin b/plugins/damas/src/META-INF/services/pitiupi.models.Plugin deleted file mode 100644 index 51af5e8..0000000 --- a/plugins/damas/src/META-INF/services/pitiupi.models.Plugin +++ /dev/null @@ -1 +0,0 @@ -pitiupi.damas.plugin.DamasPlugin diff --git a/plugins/damas/src/pitiupi/damas/GUI/BoardView.java b/plugins/damas/src/pitiupi/damas/GUI/BoardView.java deleted file mode 100644 index 2608e16..0000000 --- a/plugins/damas/src/pitiupi/damas/GUI/BoardView.java +++ /dev/null @@ -1,252 +0,0 @@ -package pitiupi.damas.GUI; - -import pitiupi.damas.game.DamasGame; -import pitiupi.damas.game.Move; -import pitiupi.damas.game.Piece; -import pitiupi.damas.game.Side; - -import javax.swing.JComponent; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; - -/** - * Tabuleiro desenhado em Swing. O lance é montado clique a clique (origem e cada pouso) e só é - * entregue a {@code onMove} quando o caminho formar um lance legal completo. - */ -final class BoardView extends JComponent { - - private static final Color LIGHT_SQUARE = new Color(238, 217, 181); - private static final Color DARK_SQUARE = new Color(148, 98, 64); - private static final Color LAST_MOVE = new Color(186, 162, 72); - private static final Color MOVABLE = new Color(90, 200, 120); - private static final Color SELECTED = new Color(250, 210, 60); - private static final Color WHITE_PIECE = new Color(245, 240, 228); - private static final Color BLACK_PIECE = new Color(44, 40, 38); - private static final Color CROWN = new Color(214, 160, 40); - - private final Consumer> onMove; - private final List partialPath = new ArrayList<>(); - private DamasGame game; - private Side viewSide = Side.WHITE; - private boolean interactive; - - BoardView(Consumer> onMove) { - this.onMove = onMove; - setPreferredSize(new Dimension(520, 520)); - addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - int square = squareAt(e.getX(), e.getY()); - if (interactive && square >= 0) { - onSquareClicked(square); - } - } - }); - } - - void setState(DamasGame game, Side viewSide, boolean interactive) { - this.game = game; - this.viewSide = viewSide != null ? viewSide : Side.WHITE; - this.interactive = interactive && game != null; - partialPath.clear(); - setCursor(Cursor.getPredefinedCursor(this.interactive ? Cursor.HAND_CURSOR : Cursor.DEFAULT_CURSOR)); - repaint(); - } - - private void onSquareClicked(int square) { - for (Move move : candidates()) { - if (!partialPath.isEmpty() && move.path().get(partialPath.size()) == square) { - partialPath.add(square); - if (move.path().size() == partialPath.size()) { - List complete = List.copyOf(partialPath); - partialPath.clear(); - onMove.accept(complete); - } - repaint(); - return; - } - } - partialPath.clear(); - if (isMovable(square)) { - partialPath.add(square); - } - repaint(); - } - - /** Lances legais que continuam o caminho já clicado. */ - private List candidates() { - List matching = new ArrayList<>(); - for (Move move : game.getLegalMoves()) { - if (move.path().size() > partialPath.size() - && move.path().subList(0, partialPath.size()).equals(partialPath)) { - matching.add(move); - } - } - return matching; - } - - private boolean isMovable(int square) { - return game.getLegalMoves().stream().anyMatch(move -> move.from() == square); - } - - private int boardSize() { - return Math.min(getWidth(), getHeight()); - } - - private int cellSize() { - return boardSize() / DamasGame.SIZE; - } - - private int originX() { - return (getWidth() - cellSize() * DamasGame.SIZE) / 2; - } - - private int originY() { - return (getHeight() - cellSize() * DamasGame.SIZE) / 2; - } - - /** Linha na tela: quem joga de pretas vê o tabuleiro girado 180°. */ - private int toView(int index) { - return viewSide == Side.WHITE ? index : DamasGame.SIZE - 1 - index; - } - - private int squareAt(int x, int y) { - int cell = cellSize(); - if (cell == 0) { - return -1; - } - int viewCol = Math.floorDiv(x - originX(), cell); - int viewRow = Math.floorDiv(y - originY(), cell); - if (viewCol < 0 || viewRow < 0 || viewCol >= DamasGame.SIZE || viewRow >= DamasGame.SIZE) { - return -1; - } - return DamasGame.square(toView(viewRow), toView(viewCol)); - } - - private int cellX(int square) { - return originX() + toView(DamasGame.colOf(square)) * cellSize(); - } - - private int cellY(int square) { - return originY() + toView(DamasGame.rowOf(square)) * cellSize(); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D g = (Graphics2D) graphics.create(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - paintSquares(g); - if (game != null) { - paintPieces(g); - if (interactive) { - paintHints(g); - } - } - g.dispose(); - } - - private void paintSquares(Graphics2D g) { - Move lastMove = game != null ? game.getLastMove() : null; - int cell = cellSize(); - for (int square = 0; square < DamasGame.SIZE * DamasGame.SIZE; square++) { - boolean dark = DamasGame.isDarkSquare(DamasGame.rowOf(square), DamasGame.colOf(square)); - boolean highlighted = lastMove != null && lastMove.path().contains(square); - g.setColor(highlighted ? LAST_MOVE : dark ? DARK_SQUARE : LIGHT_SQUARE); - g.fillRect(cellX(square), cellY(square), cell, cell); - } - } - - private void paintPieces(Graphics2D g) { - List capturedSoFar = capturedSoFar(); - Piece moving = partialPath.isEmpty() ? null : game.pieceAt(partialPath.get(0)); - for (int square = 0; square < DamasGame.SIZE * DamasGame.SIZE; square++) { - Piece piece = game.pieceAt(square); - boolean movedAway = !partialPath.isEmpty() && partialPath.get(0) == square; - if (piece != null && !movedAway) { - paintPiece(g, piece, square, capturedSoFar.contains(square)); - } - } - if (moving != null) { - paintPiece(g, moving, partialPath.get(partialPath.size() - 1), false); - } - } - - private List capturedSoFar() { - if (partialPath.size() < 2) { - return List.of(); - } - List matching = candidates(); - if (matching.isEmpty() || matching.get(0).captured().isEmpty()) { - return List.of(); - } - return matching.get(0).captured().subList(0, partialPath.size() - 1); - } - - private void paintPiece(Graphics2D g, Piece piece, int square, boolean dimmed) { - int cell = cellSize(); - int margin = cell / 8; - int size = cell - 2 * margin; - int x = cellX(square) + margin; - int y = cellY(square) + margin; - Color fill = piece.getSide() == Side.WHITE ? WHITE_PIECE : BLACK_PIECE; - Color edge = piece.getSide() == Side.WHITE ? BLACK_PIECE : WHITE_PIECE; - if (dimmed) { - fill = new Color(fill.getRed(), fill.getGreen(), fill.getBlue(), 90); - edge = new Color(edge.getRed(), edge.getGreen(), edge.getBlue(), 90); - } - g.setColor(fill); - g.fillOval(x, y, size, size); - g.setColor(edge); - g.setStroke(new BasicStroke(Math.max(1f, cell / 40f))); - g.drawOval(x, y, size, size); - g.drawOval(x + size / 6, y + size / 6, size * 2 / 3, size * 2 / 3); - if (piece.isKing()) { - paintCrown(g, x, y, size); - } - } - - private void paintCrown(Graphics2D g, int x, int y, int size) { - int left = x + size / 4; - int right = x + size * 3 / 4; - int top = y + size * 3 / 10; - int bottom = y + size * 2 / 3; - int mid = (left + right) / 2; - int inner = y + size / 2; - g.setColor(CROWN); - g.fillPolygon( - new int[]{left, left, (left + mid) / 2, mid, (mid + right) / 2, right, right}, - new int[]{bottom, top, inner, top, inner, top, bottom}, - 7 - ); - } - - private void paintHints(Graphics2D g) { - int cell = cellSize(); - g.setStroke(new BasicStroke(Math.max(2f, cell / 20f))); - if (partialPath.isEmpty()) { - g.setColor(MOVABLE); - for (Move move : game.getLegalMoves()) { - g.drawRect(cellX(move.from()) + 1, cellY(move.from()) + 1, cell - 3, cell - 3); - } - return; - } - int current = partialPath.get(partialPath.size() - 1); - g.setColor(SELECTED); - g.drawRect(cellX(current) + 1, cellY(current) + 1, cell - 3, cell - 3); - int dot = cell / 3; - for (Move move : candidates()) { - int next = move.path().get(partialPath.size()); - g.fillOval(cellX(next) + (cell - dot) / 2, cellY(next) + (cell - dot) / 2, dot, dot); - } - } -} diff --git a/plugins/damas/src/pitiupi/damas/GUI/DamasPanel.java b/plugins/damas/src/pitiupi/damas/GUI/DamasPanel.java deleted file mode 100644 index 3823157..0000000 --- a/plugins/damas/src/pitiupi/damas/GUI/DamasPanel.java +++ /dev/null @@ -1,296 +0,0 @@ -package pitiupi.damas.GUI; - -import pitiupi.application.presence.UserPeerView; -import pitiupi.control.ConnectionManager; -import pitiupi.damas.control.DamasController; -import pitiupi.damas.game.DamasGame; -import pitiupi.damas.game.Side; -import pitiupi.presentation.shell.ui.ShellUi; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.ListSelectionModel; -import javax.swing.UIManager; -import javax.swing.plaf.basic.BasicTextAreaUI; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.util.List; - -/** - * Aba do plugin: tabuleiro à esquerda e, à direita, as ações da fase atual da sessão. - */ -public final class DamasPanel extends JPanel { - - private static final String CARD_LOBBY = "lobby"; - private static final String CARD_INVITE_SENT = "inviteSent"; - private static final String CARD_INVITE_RECEIVED = "inviteReceived"; - private static final String CARD_PLAYING = "playing"; - private static final String CARD_FINISHED = "finished"; - - private final DamasController controller; - private final ConnectionManager connectionManager; - private final BoardView boardView; - - private final CardLayout cards = new CardLayout(); - private final JPanel cardHost = new JPanel(cards); - private final JTextArea noticeText = wrappedText(); - private final DefaultListModel peerModel = new DefaultListModel<>(); - private final JList peerList = new JList<>(peerModel); - private final JButton inviteButton = new JButton("Convidar"); - private final JTextArea inviteSentText = wrappedText(); - private final JTextArea inviteReceivedText = wrappedText(); - private final JTextArea playingText = wrappedText(); - private final JTextArea awayText = wrappedText(); - private final JButton resignButton = new JButton("Desistir"); - private final JTextArea finishedText = wrappedText(); - - public DamasPanel(DamasController controller, ConnectionManager connectionManager) { - this.controller = controller; - this.connectionManager = connectionManager; - this.boardView = new BoardView(controller::play); - - setLayout(new BorderLayout(8, 0)); - setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); - add(boardView, BorderLayout.CENTER); - add(buildSidePanel(), BorderLayout.EAST); - - refreshPeers(); - refresh(); - } - - private JComponent buildSidePanel() { - cardHost.add(buildLobbyCard(), CARD_LOBBY); - cardHost.add(buildInviteSentCard(), CARD_INVITE_SENT); - cardHost.add(buildInviteReceivedCard(), CARD_INVITE_RECEIVED); - cardHost.add(buildPlayingCard(), CARD_PLAYING); - cardHost.add(buildFinishedCard(), CARD_FINISHED); - - JPanel side = new JPanel(new BorderLayout(0, 8)); - side.setPreferredSize(new Dimension(220, 0)); - side.add(cardHost, BorderLayout.CENTER); - side.add(noticeText, BorderLayout.SOUTH); - return side; - } - - private JComponent buildLobbyCard() { - peerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - peerList.setCellRenderer(new DefaultListCellRenderer() { - @Override - public Component getListCellRendererComponent( - JList list, - Object value, - int index, - boolean isSelected, - boolean cellHasFocus - ) { - JLabel label = (JLabel) super.getListCellRendererComponent( - list, value, index, isSelected, cellHasFocus); - // Nomes vêm da rede: não deixar o Swing interpretar HTML. - label.putClientProperty("html.disable", Boolean.TRUE); - return label; - } - }); - peerList.addListSelectionListener(e -> updateInviteButton()); - inviteButton.addActionListener(e -> { - PeerItem selected = peerList.getSelectedValue(); - if (selected != null) { - controller.invite(selected.id(), selected.name()); - } - }); - - JPanel card = new JPanel(new BorderLayout(0, 6)); - card.add(titleLabel("Escolha um adversário"), BorderLayout.NORTH); - card.add(new JScrollPane(peerList), BorderLayout.CENTER); - card.add(inviteButton, BorderLayout.SOUTH); - return card; - } - - private JComponent buildInviteSentCard() { - return stackedCard("Convite enviado", inviteSentText, button("Cancelar", controller::cancelInvite)); - } - - private JComponent buildInviteReceivedCard() { - return stackedCard( - "Convite recebido", - inviteReceivedText, - button("Aceitar", controller::acceptInvite), - button("Recusar", controller::declineInvite) - ); - } - - private JComponent buildPlayingCard() { - resignButton.addActionListener(e -> confirmResign()); - return stackedCard("Partida", playingText, awayText, resignButton); - } - - private JComponent buildFinishedCard() { - return stackedCard( - "Fim de partida", - finishedText, - button("Jogar de novo", this::rematch), - button("Escolher outro adversário", controller::backToLobby) - ); - } - - private void confirmResign() { - if (controller.isOpponentAway()) { - controller.resign(); - return; - } - int answer = JOptionPane.showConfirmDialog( - this, - "Desistir desta partida?", - "Damas", - JOptionPane.YES_NO_OPTION - ); - if (answer == JOptionPane.YES_OPTION) { - controller.resign(); - } - } - - private void rematch() { - controller.invite(controller.getOpponentId(), controller.getOpponentName()); - } - - /** Sincroniza a tela com o estado do controller. */ - public void refresh() { - DamasController.Phase phase = controller.getPhase(); - DamasGame game = controller.getGame(); - boardView.setState(game, controller.getMySide(), controller.isMyTurn()); - - DamasController.IncomingInvite invite = controller.getIncomingInvite(); - if (invite != null) { - inviteReceivedText.setText(invite.fromName() + " convidou você para uma partida. " - + "Você jogaria de " + invite.inviterSide().opposite().getLabel() + "."); - cards.show(cardHost, CARD_INVITE_RECEIVED); - } else { - switch (phase) { - case LOBBY -> cards.show(cardHost, CARD_LOBBY); - case INVITE_SENT -> { - inviteSentText.setText("Aguardando resposta de " + controller.getOpponentName() + "…"); - cards.show(cardHost, CARD_INVITE_SENT); - } - case PLAYING -> { - updatePlayingCard(game); - cards.show(cardHost, CARD_PLAYING); - } - case FINISHED -> { - finishedText.setText(controller.getNotice()); - cards.show(cardHost, CARD_FINISHED); - } - } - } - boolean showNotice = phase != DamasController.Phase.FINISHED && !controller.getNotice().isEmpty(); - noticeText.setText(showNotice ? controller.getNotice() : ""); - noticeText.setVisible(showNotice); - updateInviteButton(); - } - - private void updatePlayingCard(DamasGame game) { - Side me = controller.getMySide(); - Side other = me.opposite(); - String turnLine = controller.isMyTurn() ? "Sua vez." : "Vez de " + controller.getOpponentName() + "."; - String captureLine = controller.isMyTurn() && !game.getLegalMoves().get(0).captured().isEmpty() - ? "\nCaptura obrigatória." - : ""; - playingText.setText( - "Você: " + me.getLabel() + " (" + game.countPieces(me) + " peças)\n" - + controller.getOpponentName() + ": " + other.getLabel() - + " (" + game.countPieces(other) + " peças)\n\n" - + turnLine + captureLine - ); - boolean away = controller.isOpponentAway(); - awayText.setText(away - ? controller.getOpponentName() + " saiu da rede. A partida continua se voltar." - : ""); - awayText.setVisible(away); - resignButton.setText(away ? "Encerrar partida" : "Desistir"); - } - - public void refreshPeers() { - PeerItem selected = peerList.getSelectedValue(); - List views = connectionManager.getPresenceService().listPeerViews(); - peerModel.clear(); - for (UserPeerView view : views) { - if (!view.isBroadcastTarget() && !view.isSelf()) { - peerModel.addElement(new PeerItem(view.getInstanceId(), view.getDisplayName())); - } - } - if (selected != null && peerModel.contains(selected)) { - peerList.setSelectedValue(selected, false); - } - updateInviteButton(); - } - - private void updateInviteButton() { - inviteButton.setEnabled(peerList.getSelectedValue() != null && controller.canInvite()); - } - - private static JButton button(String text, Runnable action) { - JButton button = new JButton(text); - button.addActionListener(e -> action.run()); - return button; - } - - private static JLabel titleLabel(String text) { - JLabel label = new JLabel(text); - label.setFont(label.getFont().deriveFont(Font.BOLD)); - return label; - } - - private static JPanel stackedCard(String title, JComponent... rows) { - JPanel stack = new JPanel(); - stack.setLayout(new BoxLayout(stack, BoxLayout.Y_AXIS)); - JLabel titleLabel = titleLabel(title); - titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT); - stack.add(titleLabel); - for (JComponent row : rows) { - stack.add(Box.createVerticalStrut(8)); - row.setAlignmentX(Component.LEFT_ALIGNMENT); - if (row instanceof JButton) { - row.setMaximumSize(new Dimension(Integer.MAX_VALUE, row.getPreferredSize().height)); - } - stack.add(row); - } - JPanel card = new JPanel(new BorderLayout()); - card.add(stack, BorderLayout.NORTH); - return card; - } - - /** Texto com quebra de linha sem HTML, pois inclui nomes vindos da rede. */ - private static JTextArea wrappedText() { - JTextArea area = new JTextArea(); - // O Nimbus pinta fundo e borda de campo de texto mesmo com setOpaque(false). - area.setUI(new BasicTextAreaUI()); - area.setEditable(false); - area.setFocusable(false); - area.setOpaque(false); - area.setBorder(null); - area.setForeground(UIManager.getColor("Label.foreground")); - area.setLineWrap(true); - area.setWrapStyleWord(true); - area.setFont(UIManager.getFont("Label.font")); - return area; - } - - private record PeerItem(String id, String name) { - @Override - public String toString() { - return name; - } - } -} diff --git a/plugins/damas/src/pitiupi/damas/control/DamasController.java b/plugins/damas/src/pitiupi/damas/control/DamasController.java deleted file mode 100644 index ca20eca..0000000 --- a/plugins/damas/src/pitiupi/damas/control/DamasController.java +++ /dev/null @@ -1,422 +0,0 @@ -package pitiupi.damas.control; - -import pitiupi.damas.game.DamasGame; -import pitiupi.damas.game.GameResult; -import pitiupi.damas.game.Side; -import pitiupi.damas.net.DamasMessage; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * Sessão de jogo: convites, lances e entrega confiável sobre UDP. - * - *

Cada mensagem enviada fica pendente até chegar o ACK e é reenviada a cada {@link #tick()}. - * O receptor confirma sempre, mesmo as duplicadas, e processa cada mensagem uma única vez. - * Lances recebidos são validados pelas regras locais antes de serem aplicados.

- * - *

Não é thread-safe: todas as chamadas devem vir da mesma thread (no plugin, a EDT).

- */ -public final class DamasController { - - public enum Phase { - LOBBY, - INVITE_SENT, - PLAYING, - FINISHED - } - - public interface Listener { - void onStateChanged(); - - /** Algo exige a atenção do jogador: convite recebido ou partida iniciada. */ - void onAttentionNeeded(); - } - - /** Convite recebido aguardando a resposta do jogador. */ - public record IncomingInvite(String gameId, String fromId, String fromName, Side inviterSide) { - } - - static final int INVITE_MAX_ATTEMPTS = 20; - static final int MESSAGE_MAX_ATTEMPTS = 120; - - private final String selfId; - private final Supplier selfName; - private final Consumer link; - private final Listener listener; - - private final List pending = new ArrayList<>(); - private final Set processed = new HashSet<>(); - private Set knownPeers = Set.of(); - private int nextSeq = 1; - - private Phase phase = Phase.LOBBY; - private String gameId; - private String opponentId; - private String opponentName; - private Side mySide; - private DamasGame game; - private boolean opponentAway; - private IncomingInvite incomingInvite; - private String notice = ""; - - public DamasController( - String selfId, - Supplier selfName, - Consumer link, - Listener listener - ) { - this.selfId = selfId; - this.selfName = selfName; - this.link = link; - this.listener = listener; - } - - public Phase getPhase() { - return phase; - } - - public DamasGame getGame() { - return game; - } - - public Side getMySide() { - return mySide; - } - - public String getOpponentId() { - return opponentId; - } - - public String getOpponentName() { - return opponentName; - } - - public boolean isOpponentAway() { - return opponentAway; - } - - public IncomingInvite getIncomingInvite() { - return incomingInvite; - } - - /** Último aviso para o jogador (recusa, fim de partida, adversário saiu…). */ - public String getNotice() { - return notice; - } - - public boolean isMyTurn() { - return phase == Phase.PLAYING && game.getTurn() == mySide; - } - - public boolean canInvite() { - return (phase == Phase.LOBBY || phase == Phase.FINISHED) && incomingInvite == null; - } - - public boolean invite(String peerId, String peerName) { - if (!canInvite()) { - return false; - } - gameId = UUID.randomUUID().toString(); - opponentId = peerId; - opponentName = peerName; - mySide = ThreadLocalRandom.current().nextBoolean() ? Side.WHITE : Side.BLACK; - game = null; - opponentAway = false; - phase = Phase.INVITE_SENT; - notice = ""; - sendReliable(DamasMessage.invite(gameId, selfId, peerId, selfName.get(), nextSeq++, mySide)); - listener.onStateChanged(); - return true; - } - - public void cancelInvite() { - if (phase != Phase.INVITE_SENT) { - return; - } - forgetCurrentGameMessages(); - sendControl(DamasMessage.Type.CANCEL); - phase = Phase.LOBBY; - notice = ""; - listener.onStateChanged(); - } - - public void acceptInvite() { - IncomingInvite invite = incomingInvite; - if (invite == null) { - return; - } - incomingInvite = null; - gameId = invite.gameId(); - opponentId = invite.fromId(); - opponentName = invite.fromName(); - mySide = invite.inviterSide().opposite(); - sendControl(DamasMessage.Type.ACCEPT); - startGame(); - } - - public void declineInvite() { - IncomingInvite invite = incomingInvite; - if (invite == null) { - return; - } - incomingInvite = null; - sendReliable(DamasMessage.control( - DamasMessage.Type.DECLINE, invite.gameId(), selfId, invite.fromId(), selfName.get(), nextSeq++)); - listener.onStateChanged(); - } - - /** - * Joga o lance local. - * - * @return {@code false} se não for a vez do jogador ou o caminho não for legal. - */ - public boolean play(List path) { - if (!isMyTurn() || game.apply(path) == null) { - return false; - } - sendReliable(DamasMessage.move(gameId, selfId, opponentId, selfName.get(), nextSeq++, path)); - finishIfGameOver(); - listener.onStateChanged(); - return true; - } - - /** Desiste da partida ou, se o adversário saiu da rede, apenas a encerra. */ - public void resign() { - if (phase != Phase.PLAYING) { - return; - } - sendControl(DamasMessage.Type.RESIGN); - phase = Phase.FINISHED; - notice = opponentAway - ? "Partida encerrada: " + opponentName + " saiu da rede." - : "Você desistiu. " + opponentName + " venceu."; - listener.onStateChanged(); - } - - public void backToLobby() { - if (phase != Phase.FINISHED) { - return; - } - phase = Phase.LOBBY; - game = null; - notice = ""; - listener.onStateChanged(); - } - - /** Reenvia o que ainda não foi confirmado. Chamar periodicamente. */ - public void tick() { - boolean changed = false; - for (Iterator it = pending.iterator(); it.hasNext(); ) { - Pending item = it.next(); - if (item.attempts >= maxAttempts(item.message)) { - it.remove(); - if (item.message.getType() == DamasMessage.Type.INVITE && isCurrentGame(item.message) - && phase == Phase.INVITE_SENT) { - phase = Phase.LOBBY; - notice = opponentName + " não respondeu ao convite."; - changed = true; - } - continue; - } - item.attempts++; - link.accept(item.message); - } - if (changed) { - listener.onStateChanged(); - } - } - - /** Atualiza a presença. O adversário que sumir pode voltar (ex.: falha rápida no Wi-Fi). */ - public void onPeersChanged(Set peerIds) { - Set previous = knownPeers; - knownPeers = Set.copyOf(peerIds); - boolean changed = false; - - if (incomingInvite != null && previous.contains(incomingInvite.fromId()) - && !peerIds.contains(incomingInvite.fromId())) { - notice = incomingInvite.fromName() + " saiu da rede; convite cancelado."; - incomingInvite = null; - changed = true; - } - if (phase == Phase.INVITE_SENT && previous.contains(opponentId) && !peerIds.contains(opponentId)) { - forgetCurrentGameMessages(); - phase = Phase.LOBBY; - notice = opponentName + " saiu da rede; convite cancelado."; - changed = true; - } - if (phase == Phase.PLAYING) { - boolean away = previous.contains(opponentId) && !peerIds.contains(opponentId) - || opponentAway && !peerIds.contains(opponentId); - if (away != opponentAway) { - opponentAway = away; - changed = true; - } - } - if (changed) { - listener.onStateChanged(); - } - } - - public void receive(DamasMessage message) { - if (!selfId.equals(message.getTo()) || message.getFrom() == null || message.getGameId() == null) { - return; - } - if (message.getType() == DamasMessage.Type.ACK) { - pending.removeIf(item -> item.message.getSeq() == message.getSeq() - && item.message.getGameId().equals(message.getGameId()) - && item.message.getTo().equals(message.getFrom())); - return; - } - link.accept(DamasMessage.ack(message, selfId)); - String key = message.getFrom() + "|" + message.getGameId() + "|" + message.getSeq(); - if (!processed.add(key)) { - return; - } - switch (message.getType()) { - case INVITE -> onInvite(message); - case ACCEPT -> onAccept(message); - case DECLINE -> onInviteRefused(message, " recusou o convite."); - case BUSY -> onInviteRefused(message, " está ocupado no momento."); - case CANCEL -> onCancel(message); - case MOVE -> onMove(message); - case RESIGN -> onResign(message); - default -> { - } - } - } - - private void onInvite(DamasMessage message) { - if (message.getInviterSide() == null) { - return; - } - if (!canInvite()) { - sendReliable(DamasMessage.control( - DamasMessage.Type.BUSY, message.getGameId(), selfId, message.getFrom(), selfName.get(), nextSeq++)); - return; - } - incomingInvite = new IncomingInvite( - message.getGameId(), message.getFrom(), message.getFromName(), message.getInviterSide()); - listener.onStateChanged(); - listener.onAttentionNeeded(); - } - - private void onAccept(DamasMessage message) { - if (phase == Phase.INVITE_SENT && isFromOpponent(message)) { - startGame(); - } - } - - private void onInviteRefused(DamasMessage message, String reason) { - if (phase == Phase.INVITE_SENT && isFromOpponent(message)) { - phase = Phase.LOBBY; - notice = opponentName + reason; - listener.onStateChanged(); - } - } - - private void onCancel(DamasMessage message) { - if (incomingInvite != null && incomingInvite.gameId().equals(message.getGameId())) { - notice = incomingInvite.fromName() + " cancelou o convite."; - incomingInvite = null; - listener.onStateChanged(); - } else if (phase == Phase.PLAYING && isFromOpponent(message)) { - // O convite foi cancelado enquanto o aceite estava a caminho. - phase = Phase.LOBBY; - game = null; - notice = opponentName + " cancelou o convite."; - listener.onStateChanged(); - } - } - - private void onMove(DamasMessage message) { - if (phase != Phase.PLAYING || !isFromOpponent(message) || message.getPath() == null || isMyTurn()) { - return; - } - if (game.apply(message.getPath()) == null) { - phase = Phase.FINISHED; - notice = "Partida interrompida: lance inválido recebido de " + opponentName + "."; - } else { - finishIfGameOver(); - } - listener.onStateChanged(); - } - - private void onResign(DamasMessage message) { - if (phase == Phase.PLAYING && isFromOpponent(message)) { - phase = Phase.FINISHED; - notice = opponentName + " desistiu. Você venceu!"; - listener.onStateChanged(); - } - } - - private void startGame() { - game = new DamasGame(); - phase = Phase.PLAYING; - opponentAway = false; - notice = ""; - listener.onStateChanged(); - listener.onAttentionNeeded(); - } - - private void finishIfGameOver() { - GameResult result = game.getResult(); - if (result == GameResult.IN_PROGRESS) { - return; - } - phase = Phase.FINISHED; - if (result == GameResult.DRAW) { - notice = "Empate: 20 lances de cada lado só com damas, sem captura."; - } else { - Side winner = result == GameResult.WHITE_WINS ? Side.WHITE : Side.BLACK; - notice = winner == mySide ? "Você venceu!" : opponentName + " venceu."; - } - } - - private boolean isFromOpponent(DamasMessage message) { - return isCurrentGame(message) && message.getFrom().equals(opponentId); - } - - private boolean isCurrentGame(DamasMessage message) { - return message.getGameId().equals(gameId); - } - - /** Um lance da partida em curso nunca é descartado: o adversário pode voltar à rede. */ - private int maxAttempts(DamasMessage message) { - return switch (message.getType()) { - case INVITE -> INVITE_MAX_ATTEMPTS; - case MOVE -> phase == Phase.PLAYING && isCurrentGame(message) ? Integer.MAX_VALUE : MESSAGE_MAX_ATTEMPTS; - default -> MESSAGE_MAX_ATTEMPTS; - }; - } - - /** Preserva o que ainda está a caminho de partidas anteriores, como o lance final. */ - private void forgetCurrentGameMessages() { - pending.removeIf(item -> isCurrentGame(item.message)); - } - - private void sendControl(DamasMessage.Type type) { - sendReliable(DamasMessage.control(type, gameId, selfId, opponentId, selfName.get(), nextSeq++)); - } - - private void sendReliable(DamasMessage message) { - pending.add(new Pending(message)); - link.accept(message); - } - - private static final class Pending { - private final DamasMessage message; - private int attempts; - - private Pending(DamasMessage message) { - this.message = message; - } - } -} diff --git a/plugins/damas/src/pitiupi/damas/game/DamasGame.java b/plugins/damas/src/pitiupi/damas/game/DamasGame.java deleted file mode 100644 index 591f07a..0000000 --- a/plugins/damas/src/pitiupi/damas/game/DamasGame.java +++ /dev/null @@ -1,271 +0,0 @@ -package pitiupi.damas.game; - -import java.util.ArrayList; -import java.util.List; - -/** - * Regras do jogo de damas brasileiro (tabuleiro 8×8), sem rede nem Swing. - * - *

Pedras andam uma casa para a frente e capturam para a frente e para trás. Damas são - * voadoras. A captura é obrigatória e vale a lei da maioria: só são legais as sequências com - * o maior número de peças; em caso de igualdade, a escolha é livre. As peças capturadas só - * saem do tabuleiro no fim da sequência e não podem ser saltadas duas vezes. A pedra que - * passa pela última linha no meio de uma captura só é promovida se terminar nela.

- * - *

Empate após 20 lances de cada lado só com damas, sem captura nem movimento de pedra.

- */ -public final class DamasGame { - - public static final int SIZE = 8; - private static final int INITIAL_ROWS = 3; - private static final int DRAW_QUIET_PLIES = 40; - private static final int[][] DIRECTIONS = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; - - private final Piece[] board = new Piece[SIZE * SIZE]; - private Side turn = Side.WHITE; - private int quietPlies; - private GameResult result = GameResult.IN_PROGRESS; - private Move lastMove; - private List legalMoves; - - public DamasGame() { - for (int row = 0; row < SIZE; row++) { - for (int col = 0; col < SIZE; col++) { - if (!isDarkSquare(row, col)) { - continue; - } - if (row < INITIAL_ROWS) { - board[square(row, col)] = Piece.BLACK_MAN; - } else if (row >= SIZE - INITIAL_ROWS) { - board[square(row, col)] = Piece.WHITE_MAN; - } - } - } - legalMoves = computeLegalMoves(); - } - - /** - * Posição arbitrária para testes: uma string por linha, com {@code w b W B} e {@code .}. - */ - static DamasGame fromRows(Side turn, String... rows) { - DamasGame game = new DamasGame(); - for (int row = 0; row < SIZE; row++) { - for (int col = 0; col < SIZE; col++) { - game.board[square(row, col)] = switch (rows[row].charAt(col)) { - case 'w' -> Piece.WHITE_MAN; - case 'W' -> Piece.WHITE_KING; - case 'b' -> Piece.BLACK_MAN; - case 'B' -> Piece.BLACK_KING; - default -> null; - }; - } - } - game.turn = turn; - game.legalMoves = game.computeLegalMoves(); - return game; - } - - public static int square(int row, int col) { - return row * SIZE + col; - } - - public static int rowOf(int square) { - return square / SIZE; - } - - public static int colOf(int square) { - return square % SIZE; - } - - /** A casa escura fica no canto inferior esquerdo de cada jogador. */ - public static boolean isDarkSquare(int row, int col) { - return (row + col) % 2 == 1; - } - - public Piece pieceAt(int square) { - return board[square]; - } - - public Side getTurn() { - return turn; - } - - public GameResult getResult() { - return result; - } - - public Move getLastMove() { - return lastMove; - } - - public List getLegalMoves() { - return legalMoves; - } - - public int countPieces(Side side) { - int count = 0; - for (Piece piece : board) { - if (piece != null && piece.getSide() == side) { - count++; - } - } - return count; - } - - /** - * Aplica o lance com este caminho. - * - * @return o lance aplicado ou {@code null} se o caminho não for legal nesta posição. - */ - public Move apply(List path) { - if (result != GameResult.IN_PROGRESS) { - return null; - } - for (Move move : legalMoves) { - if (move.path().equals(path)) { - applyLegal(move); - return move; - } - } - return null; - } - - private void applyLegal(Move move) { - Piece piece = board[move.from()]; - board[move.from()] = null; - for (int captured : move.captured()) { - board[captured] = null; - } - boolean promotes = !piece.isKing() && rowOf(move.to()) == piece.getSide().getPromotionRow(); - board[move.to()] = promotes ? piece.promoted() : piece; - - quietPlies = piece.isKing() && move.captured().isEmpty() ? quietPlies + 1 : 0; - lastMove = move; - Side mover = turn; - turn = mover.opposite(); - legalMoves = computeLegalMoves(); - - if (legalMoves.isEmpty()) { - result = mover == Side.WHITE ? GameResult.WHITE_WINS : GameResult.BLACK_WINS; - } else if (quietPlies >= DRAW_QUIET_PLIES) { - result = GameResult.DRAW; - } - } - - private List computeLegalMoves() { - List captures = new ArrayList<>(); - for (int square = 0; square < board.length; square++) { - Piece piece = board[square]; - if (piece != null && piece.getSide() == turn) { - // A peça em movimento não bloqueia o próprio caminho durante a sequência. - board[square] = null; - List path = new ArrayList<>(List.of(square)); - collectCaptures(square, piece, path, new ArrayList<>(), captures); - board[square] = piece; - } - } - if (!captures.isEmpty()) { - return keepLargestCaptures(captures); - } - List moves = new ArrayList<>(); - for (int square = 0; square < board.length; square++) { - Piece piece = board[square]; - if (piece != null && piece.getSide() == turn) { - collectSimpleMoves(square, piece, moves); - } - } - return moves; - } - - private static List keepLargestCaptures(List captures) { - int largest = 0; - for (Move move : captures) { - largest = Math.max(largest, move.captured().size()); - } - List kept = new ArrayList<>(); - for (Move move : captures) { - if (move.captured().size() == largest) { - kept.add(move); - } - } - return kept; - } - - private void collectCaptures( - int from, - Piece piece, - List path, - List captured, - List out - ) { - boolean extended = false; - for (int[] direction : DIRECTIONS) { - int victim = findVictim(from, direction, piece, captured); - if (victim < 0) { - continue; - } - int row = rowOf(victim) + direction[0]; - int col = colOf(victim) + direction[1]; - while (isOnBoard(row, col) && board[square(row, col)] == null) { - extended = true; - path.add(square(row, col)); - captured.add(victim); - collectCaptures(square(row, col), piece, path, captured, out); - captured.remove(captured.size() - 1); - path.remove(path.size() - 1); - if (!piece.isKing()) { - break; - } - row += direction[0]; - col += direction[1]; - } - } - if (!extended && !captured.isEmpty()) { - out.add(new Move(path, captured)); - } - } - - /** - * Primeira peça encontrada na direção, se puder ser capturada; {@code -1} caso contrário. - * Peças já capturadas seguem no tabuleiro e bloqueiam a passagem. - */ - private int findVictim(int from, int[] direction, Piece piece, List captured) { - int row = rowOf(from) + direction[0]; - int col = colOf(from) + direction[1]; - while (isOnBoard(row, col)) { - Piece found = board[square(row, col)]; - if (found != null) { - boolean capturable = found.getSide() != piece.getSide() && !captured.contains(square(row, col)); - return capturable ? square(row, col) : -1; - } - if (!piece.isKing()) { - return -1; - } - row += direction[0]; - col += direction[1]; - } - return -1; - } - - private void collectSimpleMoves(int from, Piece piece, List out) { - for (int[] direction : DIRECTIONS) { - if (!piece.isKing() && direction[0] != piece.getSide().getForwardRow()) { - continue; - } - int row = rowOf(from) + direction[0]; - int col = colOf(from) + direction[1]; - while (isOnBoard(row, col) && board[square(row, col)] == null) { - out.add(new Move(List.of(from, square(row, col)), List.of())); - if (!piece.isKing()) { - break; - } - row += direction[0]; - col += direction[1]; - } - } - } - - private static boolean isOnBoard(int row, int col) { - return row >= 0 && row < SIZE && col >= 0 && col < SIZE; - } -} diff --git a/plugins/damas/src/pitiupi/damas/game/GameResult.java b/plugins/damas/src/pitiupi/damas/game/GameResult.java deleted file mode 100644 index 5ed26e6..0000000 --- a/plugins/damas/src/pitiupi/damas/game/GameResult.java +++ /dev/null @@ -1,8 +0,0 @@ -package pitiupi.damas.game; - -public enum GameResult { - IN_PROGRESS, - WHITE_WINS, - BLACK_WINS, - DRAW -} diff --git a/plugins/damas/src/pitiupi/damas/game/Move.java b/plugins/damas/src/pitiupi/damas/game/Move.java deleted file mode 100644 index 5070162..0000000 --- a/plugins/damas/src/pitiupi/damas/game/Move.java +++ /dev/null @@ -1,22 +0,0 @@ -package pitiupi.damas.game; - -import java.util.List; - -/** - * Lance completo: casas percorridas (origem, pousos) e peças capturadas, na ordem do salto. - */ -public record Move(List path, List captured) { - - public Move { - path = List.copyOf(path); - captured = List.copyOf(captured); - } - - public int from() { - return path.get(0); - } - - public int to() { - return path.get(path.size() - 1); - } -} diff --git a/plugins/damas/src/pitiupi/damas/game/Piece.java b/plugins/damas/src/pitiupi/damas/game/Piece.java deleted file mode 100644 index f9afc2f..0000000 --- a/plugins/damas/src/pitiupi/damas/game/Piece.java +++ /dev/null @@ -1,28 +0,0 @@ -package pitiupi.damas.game; - -public enum Piece { - WHITE_MAN(Side.WHITE, false), - WHITE_KING(Side.WHITE, true), - BLACK_MAN(Side.BLACK, false), - BLACK_KING(Side.BLACK, true); - - private final Side side; - private final boolean king; - - Piece(Side side, boolean king) { - this.side = side; - this.king = king; - } - - public Side getSide() { - return side; - } - - public boolean isKing() { - return king; - } - - public Piece promoted() { - return side == Side.WHITE ? WHITE_KING : BLACK_KING; - } -} diff --git a/plugins/damas/src/pitiupi/damas/game/Side.java b/plugins/damas/src/pitiupi/damas/game/Side.java deleted file mode 100644 index c5dfa8e..0000000 --- a/plugins/damas/src/pitiupi/damas/game/Side.java +++ /dev/null @@ -1,35 +0,0 @@ -package pitiupi.damas.game; - -/** - * Lado de um jogador. As brancas começam e sobem o tabuleiro (linha 7 → linha 0). - */ -public enum Side { - WHITE("brancas", -1, 0), - BLACK("pretas", 1, 7); - - private final String label; - private final int forwardRow; - private final int promotionRow; - - Side(String label, int forwardRow, int promotionRow) { - this.label = label; - this.forwardRow = forwardRow; - this.promotionRow = promotionRow; - } - - public String getLabel() { - return label; - } - - public int getForwardRow() { - return forwardRow; - } - - public int getPromotionRow() { - return promotionRow; - } - - public Side opposite() { - return this == WHITE ? BLACK : WHITE; - } -} diff --git a/plugins/damas/src/pitiupi/damas/net/DamasMessage.java b/plugins/damas/src/pitiupi/damas/net/DamasMessage.java deleted file mode 100644 index a0014d9..0000000 --- a/plugins/damas/src/pitiupi/damas/net/DamasMessage.java +++ /dev/null @@ -1,106 +0,0 @@ -package pitiupi.damas.net; - -import pitiupi.damas.game.Side; -import pitiupi.models.Messages.Message; - -import java.util.List; - -/** - * Mensagem do protocolo de damas. Viaja em UDP multicast: {@code to} indica o destinatário e os - * demais peers a ignoram. Exceto {@link Type#ACK}, toda mensagem é confirmada e retransmitida. - */ -public class DamasMessage extends Message { - - private static final long serialVersionUID = 1L; - - public enum Type { - INVITE, - ACCEPT, - DECLINE, - BUSY, - CANCEL, - MOVE, - RESIGN, - ACK - } - - private final Type type; - private final String gameId; - private final String from; - private final String to; - private final String fromName; - private final int seq; - private final Side inviterSide; - private final int[] path; - - private DamasMessage( - Type type, - String gameId, - String from, - String to, - String fromName, - int seq, - Side inviterSide, - int[] path - ) { - this.type = type; - this.gameId = gameId; - this.from = from; - this.to = to; - this.fromName = fromName; - this.seq = seq; - this.inviterSide = inviterSide; - this.path = path; - } - - public static DamasMessage invite(String gameId, String from, String to, String fromName, int seq, Side inviterSide) { - return new DamasMessage(Type.INVITE, gameId, from, to, fromName, seq, inviterSide, null); - } - - public static DamasMessage move(String gameId, String from, String to, String fromName, int seq, List path) { - int[] squares = path.stream().mapToInt(Integer::intValue).toArray(); - return new DamasMessage(Type.MOVE, gameId, from, to, fromName, seq, null, squares); - } - - /** ACCEPT, DECLINE, BUSY, CANCEL ou RESIGN. */ - public static DamasMessage control(Type type, String gameId, String from, String to, String fromName, int seq) { - return new DamasMessage(type, gameId, from, to, fromName, seq, null, null); - } - - public static DamasMessage ack(DamasMessage received, String from) { - return new DamasMessage(Type.ACK, received.gameId, from, received.from, null, received.seq, null, null); - } - - public Type getType() { - return type; - } - - public String getGameId() { - return gameId; - } - - public String getFrom() { - return from; - } - - public String getTo() { - return to; - } - - public String getFromName() { - return fromName; - } - - public int getSeq() { - return seq; - } - - public Side getInviterSide() { - return inviterSide; - } - - /** Caminho do lance ou {@code null} se a mensagem não for {@link Type#MOVE}. */ - public List getPath() { - return path == null ? null : java.util.Arrays.stream(path).boxed().toList(); - } -} diff --git a/plugins/damas/src/pitiupi/damas/plugin/DamasPlugin.java b/plugins/damas/src/pitiupi/damas/plugin/DamasPlugin.java deleted file mode 100644 index 5a01046..0000000 --- a/plugins/damas/src/pitiupi/damas/plugin/DamasPlugin.java +++ /dev/null @@ -1,162 +0,0 @@ -package pitiupi.damas.plugin; - -import pitiupi.api.plugin.PeerActionsRegistrar; -import pitiupi.api.plugin.PluginWorkspace; -import pitiupi.application.messaging.MessageDispatcher; -import pitiupi.application.messaging.SendTarget; -import pitiupi.application.messaging.TransportMode; -import pitiupi.application.peeractions.PeerAction; -import pitiupi.application.peeractions.PeerActionTarget; -import pitiupi.application.peeractions.PeerTarget; -import pitiupi.control.ConnectionManager; -import pitiupi.damas.GUI.DamasPanel; -import pitiupi.damas.control.DamasController; -import pitiupi.damas.net.DamasMessage; -import pitiupi.models.Messages.Message; -import pitiupi.models.Plugin; -import pitiupi.models.User; - -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -public class DamasPlugin extends Plugin { - - private static final int RESEND_INTERVAL_MS = 500; - - private ConnectionManager connectionManager; - private PluginWorkspace workspace; - private DamasController controller; - private DamasPanel panel; - - @Override - public void createPlugin(ConnectionManager connectionManager, PluginWorkspace workspace) { - this.connectionManager = connectionManager; - this.workspace = workspace; - this.controller = new DamasController( - connectionManager.getHeartbeatManager().getInstanceId(), - connectionManager::getUserName, - this::send, - new DamasController.Listener() { - @Override - public void onStateChanged() { - panel.refresh(); - updateStatusBar(); - } - - @Override - public void onAttentionNeeded() { - openTab(); - } - } - ); - this.panel = new DamasPanel(controller, connectionManager); - bindShellWorkspaceContent(panel); - installPeerActions(workspace.peerActions()); - - connectionManager.addPeerListener(peers -> { - Set ids = peers.stream().map(User::getInstanceId).collect(Collectors.toSet()); - SwingUtilities.invokeLater(() -> { - controller.onPeersChanged(ids); - panel.refreshPeers(); - }); - }); - new Timer(RESEND_INTERVAL_MS, e -> controller.tick()).start(); - } - - @Override - public void installPeerActions(PeerActionsRegistrar registrar) { - registrar.register(PeerAction.of( - "damas.open", - "Abrir damas", - PeerActionTarget.ALL_PEERS, - target -> openTab() - )); - registrar.register(PeerAction.of( - "damas.invite", - "Convidar para uma partida", - PeerActionTarget.SINGLE_PEER, - this::inviteFromPeerList - )); - } - - private void inviteFromPeerList(PeerTarget target) { - openTab(); - if (target instanceof PeerTarget.Single single) { - controller.invite(single.peer().getInstanceId(), single.peer().getDisplayName()); - } - } - - private void openTab() { - workspace.openOrFocusTab(getIdentifier(), getDisplayName()); - } - - /** Com a aba fechada, a barra de status é o que avisa sobre convite e vez de jogar. */ - private void updateStatusBar() { - String text = statusBarText(); - if (text != null) { - workspace.setStatusMessage(text); - } - } - - private String statusBarText() { - if (controller.getIncomingInvite() != null) { - return "Damas: " + controller.getIncomingInvite().fromName() + " convidou você para uma partida"; - } - return switch (controller.getPhase()) { - case LOBBY -> null; - case INVITE_SENT -> "Damas: aguardando resposta de " + controller.getOpponentName(); - case PLAYING -> controller.isMyTurn() - ? "Damas: sua vez contra " + controller.getOpponentName() - : "Damas: vez de " + controller.getOpponentName(); - case FINISHED -> "Damas: " + controller.getNotice(); - }; - } - - /** - * Multicast é o único transporte que funciona sempre que o peer aparece na lista, pois é - * o caminho do heartbeat. A entrega confiável fica a cargo do {@link DamasController}. - */ - private void send(DamasMessage message) { - MessageDispatcher.send(connectionManager, message, SendTarget.broadcastAll(), TransportMode.MULTICAST_UDP); - } - - @Override - public List> getMessages() { - return List.of(DamasMessage.class); - } - - @Override - public void receiveMessage(Message message) { - if (message instanceof DamasMessage damasMessage) { - SwingUtilities.invokeLater(() -> controller.receive(damasMessage)); - } - } - - @Override - public String getName() { - return "Damas"; - } - - @Override - public String getDisplayName() { - return "Damas"; - } - - @Override - public String getAuthor() { - return "Felipe Chaves"; - } - - @Override - public String getVersion() { - return "1"; - } - - @Override - public String getIdentifier() { - return "Pitiupi.Damas"; - } -} diff --git a/plugins/damas/test/pitiupi/damas/control/DamasControllerTest.java b/plugins/damas/test/pitiupi/damas/control/DamasControllerTest.java deleted file mode 100644 index 54866c8..0000000 --- a/plugins/damas/test/pitiupi/damas/control/DamasControllerTest.java +++ /dev/null @@ -1,312 +0,0 @@ -package pitiupi.damas.control; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import pitiupi.damas.game.Move; -import pitiupi.damas.game.Side; -import pitiupi.damas.net.DamasMessage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.List; -import java.util.Random; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class DamasControllerTest { - - /** Rede simulada em multicast: todos recebem tudo, inclusive o eco do próprio envio. */ - private final Deque wire = new ArrayDeque<>(); - private Random loss; - private double lossRate; - private int attentionA; - private int attentionB; - private DamasController a; - private DamasController b; - private DamasController c; - - @BeforeEach - void setUp() { - lossRate = 0; - loss = new Random(42); - a = controller("a", () -> attentionA++); - b = controller("b", () -> attentionB++); - c = controller("c", () -> { }); - } - - private DamasController controller(String id, Runnable onAttention) { - return new DamasController(id, () -> id.toUpperCase(), wire::add, new DamasController.Listener() { - @Override - public void onStateChanged() { - } - - @Override - public void onAttentionNeeded() { - onAttention.run(); - } - }); - } - - /** Entrega o que está na rede, passando pela serialização real e descartando conforme a perda. */ - private void deliver() { - for (int guard = 0; guard < 10_000 && !wire.isEmpty(); guard++) { - DamasMessage message = wire.poll(); - for (DamasController target : List.of(a, b, c)) { - if (loss.nextDouble() >= lossRate) { - target.receive(roundTrip(message)); - } - } - } - } - - private void settle() { - deliver(); - for (int i = 0; i < 200; i++) { - a.tick(); - b.tick(); - c.tick(); - deliver(); - } - } - - private static DamasMessage roundTrip(DamasMessage message) { - try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(message.toByteArray()))) { - return (DamasMessage) in.readObject(); - } catch (IOException | ClassNotFoundException e) { - throw new AssertionError(e); - } - } - - private void startGame() { - assertTrue(a.invite("b", "B")); - deliver(); - b.acceptInvite(); - deliver(); - } - - private DamasController whitePlayer() { - return a.getMySide() == Side.WHITE ? a : b; - } - - private DamasController blackPlayer() { - return a.getMySide() == Side.WHITE ? b : a; - } - - @Test - void acceptedInviteStartsGameWithOppositeSides() { - startGame(); - assertEquals(DamasController.Phase.PLAYING, a.getPhase()); - assertEquals(DamasController.Phase.PLAYING, b.getPhase()); - assertEquals(a.getMySide().opposite(), b.getMySide()); - assertEquals("B", a.getOpponentName()); - assertEquals("A", b.getOpponentName()); - assertTrue(attentionA > 0 && attentionB > 0); - } - - @Test - void thirdPeerIgnoresTheConversation() { - startGame(); - assertEquals(DamasController.Phase.LOBBY, c.getPhase()); - assertNull(c.getIncomingInvite()); - } - - @Test - void declinedInviteReturnsInviterToLobby() { - a.invite("b", "B"); - deliver(); - b.declineInvite(); - deliver(); - assertEquals(DamasController.Phase.LOBBY, a.getPhase()); - assertEquals("B recusou o convite.", a.getNotice()); - assertNull(b.getIncomingInvite()); - } - - @Test - void cancelledInviteDisappearsFromInvitee() { - a.invite("b", "B"); - deliver(); - assertNotNull(b.getIncomingInvite()); - a.cancelInvite(); - deliver(); - assertNull(b.getIncomingInvite()); - } - - @Test - void inviteWhileBusyIsAnsweredAutomatically() { - startGame(); - assertTrue(c.invite("b", "B")); - deliver(); - assertEquals(DamasController.Phase.LOBBY, c.getPhase()); - assertEquals("B está ocupado no momento.", c.getNotice()); - assertEquals(DamasController.Phase.PLAYING, b.getPhase()); - } - - @Test - void movesReachOpponentAndAlternateTurns() { - startGame(); - DamasController white = whitePlayer(); - DamasController black = blackPlayer(); - assertTrue(white.isMyTurn()); - assertFalse(black.isMyTurn()); - assertFalse(black.play(black.getGame().getLegalMoves().get(0).path())); - - Move move = white.getGame().getLegalMoves().get(0); - assertTrue(white.play(move.path())); - deliver(); - assertEquals(move, black.getGame().getLastMove()); - assertTrue(black.isMyTurn()); - } - - @Test - void duplicatedMoveIsAppliedOnce() { - startGame(); - DamasController white = whitePlayer(); - DamasController black = blackPlayer(); - white.play(white.getGame().getLegalMoves().get(0).path()); - DamasMessage sent = wire.peek(); - deliver(); - black.receive(sent); - deliver(); - assertTrue(black.isMyTurn()); - assertEquals(DamasController.Phase.PLAYING, black.getPhase()); - } - - @Test - void wholeGameStaysInSyncOverLossyNetwork() { - lossRate = 0.4; - a.invite("b", "B"); - settle(); - b.acceptInvite(); - settle(); - assertEquals(DamasController.Phase.PLAYING, a.getPhase()); - - Random choice = new Random(7); - for (int ply = 0; ply < 400 && a.getPhase() == DamasController.Phase.PLAYING; ply++) { - DamasController mover = a.isMyTurn() ? a : b; - assertTrue(mover.isMyTurn(), "um dos jogadores deve ter a vez"); - List moves = mover.getGame().getLegalMoves(); - assertTrue(mover.play(moves.get(choice.nextInt(moves.size())).path())); - settle(); - assertEquals(a.getGame().getLastMove(), b.getGame().getLastMove()); - assertEquals(a.getGame().getTurn(), b.getGame().getTurn()); - assertEquals(a.getGame().getLegalMoves(), b.getGame().getLegalMoves()); - } - assertEquals(a.getPhase(), b.getPhase()); - } - - @Test - void unansweredInviteTimesOut() { - lossRate = 1; - a.invite("b", "B"); - for (int i = 0; i <= DamasController.INVITE_MAX_ATTEMPTS; i++) { - a.tick(); - } - assertEquals(DamasController.Phase.LOBBY, a.getPhase()); - assertEquals("B não respondeu ao convite.", a.getNotice()); - } - - @Test - void illegalMoveFromOpponentEndsGameWithoutApplyingIt() { - startGame(); - DamasController white = whitePlayer(); - DamasController black = blackPlayer(); - String blackId = black == a ? "a" : "b"; - String whiteId = white == a ? "a" : "b"; - String gameId = gameIdOf(white, whiteId, blackId); - black.receive(DamasMessage.move(gameId, whiteId, blackId, "X", 999, List.of(0, 63))); - assertEquals(DamasController.Phase.FINISHED, black.getPhase()); - assertEquals(12, black.getGame().countPieces(Side.WHITE)); - } - - private String gameIdOf(DamasController white, String whiteId, String blackId) { - white.play(white.getGame().getLegalMoves().get(0).path()); - DamasMessage sent = wire.poll(); - wire.clear(); - return sent.getGameId(); - } - - @Test - void forgedMoveFromThirdPeerIsIgnored() { - startGame(); - DamasController black = blackPlayer(); - String blackId = black == a ? "a" : "b"; - DamasController white = whitePlayer(); - white.play(white.getGame().getLegalMoves().get(0).path()); - DamasMessage real = wire.poll(); - wire.clear(); - black.receive(DamasMessage.move(real.getGameId(), "c", blackId, "C", 1000, real.getPath())); - assertFalse(black.isMyTurn()); - assertEquals(DamasController.Phase.PLAYING, black.getPhase()); - } - - @Test - void resignFinishesBothSides() { - startGame(); - a.resign(); - deliver(); - assertEquals(DamasController.Phase.FINISHED, a.getPhase()); - assertEquals(DamasController.Phase.FINISHED, b.getPhase()); - assertEquals("A desistiu. Você venceu!", b.getNotice()); - } - - @Test - void opponentLeavingMarksAwayAndReturningClearsIt() { - a.onPeersChanged(Set.of("b")); - startGame(); - a.onPeersChanged(Set.of()); - assertTrue(a.isOpponentAway()); - assertEquals(DamasController.Phase.PLAYING, a.getPhase()); - a.onPeersChanged(Set.of("b")); - assertFalse(a.isOpponentAway()); - } - - @Test - void refusedRematchLeavesNoStaleBoard() { - startGame(); - a.resign(); - deliver(); - a.invite("b", "B"); - deliver(); - b.declineInvite(); - deliver(); - assertEquals(DamasController.Phase.LOBBY, a.getPhase()); - assertNull(a.getGame()); - } - - @Test - void cancellingRematchStillDeliversLastMessageOfPreviousGame() { - startGame(); - lossRate = 1; - a.resign(); - deliver(); - assertEquals(DamasController.Phase.PLAYING, b.getPhase()); - a.invite("c", "C"); - a.cancelInvite(); - lossRate = 0; - settle(); - assertEquals(DamasController.Phase.FINISHED, b.getPhase()); - } - - @Test - void rematchWorksAfterGameEnds() { - startGame(); - a.resign(); - deliver(); - assertTrue(a.invite("b", "B")); - deliver(); - assertNotNull(b.getIncomingInvite()); - b.acceptInvite(); - deliver(); - assertEquals(DamasController.Phase.PLAYING, a.getPhase()); - assertEquals(DamasController.Phase.PLAYING, b.getPhase()); - assertEquals(12, a.getGame().countPieces(Side.WHITE)); - } -} diff --git a/plugins/damas/test/pitiupi/damas/game/DamasGameTest.java b/plugins/damas/test/pitiupi/damas/game/DamasGameTest.java deleted file mode 100644 index 051116e..0000000 --- a/plugins/damas/test/pitiupi/damas/game/DamasGameTest.java +++ /dev/null @@ -1,248 +0,0 @@ -package pitiupi.damas.game; - -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class DamasGameTest { - - private static int sq(int row, int col) { - return DamasGame.square(row, col); - } - - @Test - void initialPositionHasTwelvePiecesAndSevenMovesForWhite() { - DamasGame game = new DamasGame(); - assertEquals(12, game.countPieces(Side.WHITE)); - assertEquals(12, game.countPieces(Side.BLACK)); - assertEquals(Side.WHITE, game.getTurn()); - assertEquals(7, game.getLegalMoves().size()); - } - - @Test - void lowerLeftCornerIsDarkForWhite() { - assertTrue(DamasGame.isDarkSquare(7, 0)); - assertFalse(DamasGame.isDarkSquare(7, 7)); - } - - @Test - void manCannotMoveBackwards() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "b.......", - "........", - "........", - "...w....", - "........", - "........", - "........"); - assertNull(game.apply(List.of(sq(4, 3), sq(5, 2)))); - assertNotNull(game.apply(List.of(sq(4, 3), sq(3, 2)))); - } - - @Test - void captureIsMandatoryAndManCapturesBackwards() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "........", - "........", - "..w.....", - "...b....", - "........", - ".w......", - "........"); - assertEquals(1, game.getLegalMoves().size()); - assertNull(game.apply(List.of(sq(6, 1), sq(5, 0)))); - Move move = game.apply(List.of(sq(3, 2), sq(5, 4))); - assertEquals(List.of(sq(4, 3)), move.captured()); - assertNull(game.pieceAt(sq(4, 3))); - } - - @Test - void majorityRuleForcesLongestSequence() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "........", - "...b....", - "........", - "...b.b..", - "....w...", - "........", - "........"); - assertEquals(1, game.getLegalMoves().size()); - assertEquals(List.of(sq(5, 4), sq(3, 2), sq(1, 4)), game.getLegalMoves().get(0).path()); - } - - @Test - void capturedPiecesCannotBeJumpedTwiceAndOriginCountsAsEmpty() { - // Ciclo de quatro saltos que termina na origem, sem repetir a primeira peça. - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "........", - ".b.b....", - "........", - ".b.b....", - "..w.....", - "........", - "........"); - assertEquals(2, game.getLegalMoves().size()); - Move move = game.apply(List.of(sq(5, 2), sq(3, 4), sq(1, 2), sq(3, 0), sq(5, 2))); - assertEquals(4, move.captured().size()); - assertEquals(0, game.countPieces(Side.BLACK)); - } - - @Test - void flyingKingMayLandOnAnySquareBehindTheCapturedPiece() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "........", - "........", - "........", - "...b....", - "........", - ".W......", - "........"); - assertEquals(4, game.getLegalMoves().size()); - for (Move move : game.getLegalMoves()) { - assertEquals(List.of(sq(4, 3)), move.captured()); - } - } - - @Test - void flyingKingMovesAnyDistanceButNotOverOwnPieces() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "........", - "........", - "........", - "........", - "..w.....", - "........", - "W......b"); - assertNotNull(game.getLegalMoves().stream() - .filter(m -> m.from() == sq(7, 0)).findAny().orElse(null)); - assertTrue(game.getLegalMoves().stream().noneMatch(m -> m.from() == sq(7, 0) && m.to() == sq(4, 3))); - - DamasGame open = DamasGame.fromRows(Side.WHITE, - "........", - "........", - "........", - "........", - "........", - "........", - "........", - "W......b"); - assertNotNull(open.apply(List.of(sq(7, 0), sq(0, 7)))); - } - - @Test - void manReachingLastRowPromotes() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "..w.....", - "........", - "........", - "........", - "........", - "........", - "b......."); - game.apply(List.of(sq(1, 2), sq(0, 1))); - assertEquals(Piece.WHITE_KING, game.pieceAt(sq(0, 1))); - } - - @Test - void manPassingLastRowDuringCaptureDoesNotPromote() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "..b.b...", - ".w......", - "........", - "........", - "........", - "........", - "...b...."); - Move move = game.getLegalMoves().get(0); - assertEquals(List.of(sq(2, 1), sq(0, 3), sq(2, 5)), move.path()); - game.apply(move.path()); - assertEquals(Piece.WHITE_MAN, game.pieceAt(sq(2, 5))); - } - - @Test - void playerWithoutMovesLoses() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - "........", - "..b.....", - ".w......", - "........", - "........", - "........", - "........", - "........"); - game.apply(List.of(sq(2, 1), sq(0, 3))); - assertEquals(GameResult.WHITE_WINS, game.getResult()); - assertTrue(game.getLegalMoves().isEmpty()); - assertNull(game.apply(List.of(sq(0, 3), sq(1, 2)))); - } - - @Test - void twentyQuietKingMovesEachIsADraw() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - ".B......", - "........", - "........", - "........", - "........", - "........", - "........", - "W......."); - int[][] whiteSquares = {{7, 0}, {6, 1}}; - int[][] blackSquares = {{0, 1}, {1, 0}}; - for (int ply = 0; ply < 40; ply++) { - assertEquals(GameResult.IN_PROGRESS, game.getResult()); - int[][] squares = ply % 2 == 0 ? whiteSquares : blackSquares; - int[] from = squares[ply % 4 < 2 ? 0 : 1]; - int[] to = squares[ply % 4 < 2 ? 1 : 0]; - assertNotNull(game.apply(List.of(sq(from[0], from[1]), sq(to[0], to[1])))); - } - assertEquals(GameResult.DRAW, game.getResult()); - } - - @Test - void manMoveResetsTheDrawCount() { - DamasGame game = DamasGame.fromRows(Side.WHITE, - ".B......", - "........", - "........", - "........", - "........", - "w.......", - "........", - "..W....."); - for (int ply = 0; ply < 38; ply++) { - boolean out = ply % 4 < 2; - if (ply % 2 == 0) { - game.apply(out ? List.of(sq(7, 2), sq(6, 3)) : List.of(sq(6, 3), sq(7, 2))); - } else { - game.apply(out ? List.of(sq(0, 1), sq(1, 2)) : List.of(sq(1, 2), sq(0, 1))); - } - } - assertNotNull(game.apply(List.of(sq(5, 0), sq(4, 1)))); - // Sem zerar, estes dois lances de dama completariam os 40 e dariam empate. - assertNotNull(game.apply(List.of(sq(1, 2), sq(0, 1)))); - assertNotNull(game.apply(List.of(sq(6, 3), sq(7, 2)))); - assertEquals(GameResult.IN_PROGRESS, game.getResult()); - } - - @Test - void illegalPathIsRejectedWithoutChangingTurn() { - DamasGame game = new DamasGame(); - assertNull(game.apply(List.of(sq(5, 0), sq(3, 2)))); - assertEquals(Side.WHITE, game.getTurn()); - } -}