removendo arquivos da ide e plugin de damas
This commit is contained in:
1 parent
49cf3760a0
commit
e21b11dac6
54 files changed
+10
-4337
No files matched your search
+1
-1
@@ -2,7 +2,7 @@
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/damas.iml" filepath="$PROJECT_DIR$/damas.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/pitiupi.iml" filepath="$PROJECT_DIR$/.idea/pitiupi.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+9
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Generated
-107
@@ -1,107 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="AutoImportSettings">
|
||||
<option name="autoReloadType" value="SELECTIVE" />
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="184f7582-9491-4541-9ea8-677e31b83cd6" name="Changes" comment="">
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/control/ServerManager.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/models/Messages/ConnectionRequestMessage.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/models/Messages/UdpConnectionMessage.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/servers/ClosedConnectionException.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/servers/ConnectionData.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/servers/ServerNotFoundException.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/servers/TcpClient.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/servers/TcpServer.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/servers/UdpClient.java" afterDir="false" />
|
||||
<change afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/net/servers/UdpServer.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pitiupi/src/pitiupi/control/ConnectionManager.java" beforeDir="false" afterPath="$PROJECT_DIR$/pitiupi/src/pitiupi/control/ConnectionManager.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/plugins/damas/build/built-jar.properties" beforeDir="false" afterPath="$PROJECT_DIR$/plugins/damas/build/built-jar.properties" afterDir="false" />
|
||||
</list>
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="Git.Settings">
|
||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
||||
</component>
|
||||
<component name="ProjectColorInfo">{
|
||||
"associatedIndex": 2,
|
||||
"fromUser": false
|
||||
}</component>
|
||||
<component name="ProjectId" id="3GjM8jvhMxaHpSRoyB7jkVQR4Bc" />
|
||||
<component name="ProjectViewState">
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent"><![CDATA[{
|
||||
"keyToString": {
|
||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
|
||||
"RunOnceActivity.git.unshallow": "true",
|
||||
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
|
||||
"codeWithMe.voiceChat.enabledByDefault": "false",
|
||||
"git-widget-placeholder": "rebase/servidores-tcp-e-udp",
|
||||
"ignore.virus.scanning.warn.message": "true",
|
||||
"kotlin-language-version-configured": "true",
|
||||
"last_opened_file_path": "C:/Users/Gustavo/OneDrive/Documentos/Faculdade/2026_2/Monitoria/pitiupi",
|
||||
"node.js.detected.package.eslint": "true",
|
||||
"node.js.detected.package.tslint": "true",
|
||||
"node.js.selected.package.eslint": "(autodetect)",
|
||||
"node.js.selected.package.tslint": "(autodetect)",
|
||||
"nodejs_package_manager_path": "npm",
|
||||
"project.structure.last.edited": "Project",
|
||||
"project.structure.proportion": "0.0",
|
||||
"project.structure.side.proportion": "0.0",
|
||||
"run.code.analysis.last.selected.profile": "pProject Default",
|
||||
"settings.editor.selected.configurable": "preferences.lookFeel"
|
||||
}
|
||||
}]]></component>
|
||||
<component name="RecentsManager">
|
||||
<key name="CopyFile.RECENT_KEYS">
|
||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\plugins\ping" />
|
||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\pitiupi\plugins" />
|
||||
</key>
|
||||
<key name="MoveFile.RECENT_KEYS">
|
||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\plugins\ping" />
|
||||
<recent name="C:\Users\Gustavo\OneDrive\Documentos\Faculdade\2026_2\Monitoria\pitiupi\pitiupi\plugins" />
|
||||
</key>
|
||||
</component>
|
||||
<component name="RunManager">
|
||||
<configuration default="true" type="JetRunConfigurationType">
|
||||
<module name="pitiupi" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration default="true" type="KotlinStandaloneScriptRunConfigurationType">
|
||||
<module name="pitiupi" />
|
||||
<option name="filePath" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
<component name="SharedIndexes">
|
||||
<attachedChunks>
|
||||
<set>
|
||||
<option value="bundled-jdk-30f59d01ecdd-37e91769500f-intellij.indexing.shared.core-IU-261.26222.65" />
|
||||
<option value="bundled-js-predefined-d6986cc7102b-31caf2ab9e3c-JavaScript-IU-261.26222.65" />
|
||||
</set>
|
||||
</attachedChunks>
|
||||
</component>
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="184f7582-9491-4541-9ea8-677e31b83cd6" name="Changes" comment="" />
|
||||
<created>1784480367533</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1784480367533</updated>
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
<component name="TypeScriptGeneratedFilesManager">
|
||||
<option name="version" value="3" />
|
||||
</component>
|
||||
</project>
|
||||
BIN
Binary file not shown.
Generated
-10
@@ -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
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
<component name="libraryTable">
|
||||
<library name="pitiupi.damas">
|
||||
<CLASSES>
|
||||
<root url="jar://$PROJECT_DIR$/dist/pitiupi.damas.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</component>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="openjdk-26" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -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`) |
|
||||
@@ -1,27 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project name="pitiupi.damas" default="default" basedir=".">
|
||||
<description>Builds, tests, and runs the project pitiupi.damas.</description>
|
||||
<import file="nbproject/build-impl.xml"/>
|
||||
|
||||
<property name="junit.standalone" location="../../pitiupi/test/lib/junit-platform-console-standalone-1.10.2.jar"/>
|
||||
|
||||
<target name="test" depends="jar" description="JUnit 5 (console launcher)">
|
||||
<mkdir dir="${build.test.classes.dir}"/>
|
||||
<javac srcdir="test"
|
||||
destdir="${build.test.classes.dir}"
|
||||
classpath="${run.classpath}:${junit.standalone}"
|
||||
includeantruntime="false"
|
||||
source="17"
|
||||
target="17"
|
||||
encoding="UTF-8"/>
|
||||
<java classname="org.junit.platform.console.ConsoleLauncher" fork="true" failonerror="true">
|
||||
<classpath>
|
||||
<pathelement path="${build.test.classes.dir}"/>
|
||||
<pathelement path="${run.classpath}"/>
|
||||
<pathelement location="${junit.standalone}"/>
|
||||
</classpath>
|
||||
<arg value="--scan-classpath"/>
|
||||
<arg value="${build.test.classes.dir}"/>
|
||||
</java>
|
||||
</target>
|
||||
</project>
|
||||
@@ -1,6 +0,0 @@
|
||||
#Sun, 08 Nov 2026 16:11:59 -0300
|
||||
|
||||
|
||||
C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\pitiupi\\plugins\\damas=
|
||||
|
||||
C\:\\Users\\Gustavo\\OneDrive\\Documentos\\Faculdade\\2026_2\\Monitoria\\pitiupi\\pitiupi=
|
||||
@@ -1 +0,0 @@
|
||||
pitiupi.damas.plugin.DamasPlugin
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="module-library">
|
||||
<library>
|
||||
<CLASSES>
|
||||
<root url="jar://$MODULE_DIR$/../../pitiupi/dist/pitiupi.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC />
|
||||
<SOURCES />
|
||||
</library>
|
||||
</orderEntry>
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="pitiupi.damas" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
Vendored
BIN
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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
|
||||
@@ -1,25 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://www.netbeans.org/ns/project/1">
|
||||
<type>org.netbeans.modules.java.j2seproject</type>
|
||||
<configuration>
|
||||
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
|
||||
<name>pitiupi.damas</name>
|
||||
<source-roots>
|
||||
<root id="src.dir"/>
|
||||
</source-roots>
|
||||
<test-roots>
|
||||
<root id="test.src.dir"/>
|
||||
</test-roots>
|
||||
</data>
|
||||
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
|
||||
<reference>
|
||||
<foreign-project>pitiupi</foreign-project>
|
||||
<artifact-type>jar</artifact-type>
|
||||
<script>build.xml</script>
|
||||
<target>jar</target>
|
||||
<clean-target>clean</clean-target>
|
||||
<id>jar</id>
|
||||
</reference>
|
||||
</references>
|
||||
</configuration>
|
||||
</project>
|
||||
@@ -1 +0,0 @@
|
||||
pitiupi.damas.plugin.DamasPlugin
|
||||
@@ -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<List<Integer>> onMove;
|
||||
private final List<Integer> partialPath = new ArrayList<>();
|
||||
private DamasGame game;
|
||||
private Side viewSide = Side.WHITE;
|
||||
private boolean interactive;
|
||||
|
||||
BoardView(Consumer<List<Integer>> 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<Integer> 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<Move> candidates() {
|
||||
List<Move> 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<Integer> 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<Integer> capturedSoFar() {
|
||||
if (partialPath.size() < 2) {
|
||||
return List.of();
|
||||
}
|
||||
List<Move> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<PeerItem> peerModel = new DefaultListModel<>();
|
||||
private final JList<PeerItem> 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<UserPeerView> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.</p>
|
||||
*
|
||||
* <p>Não é thread-safe: todas as chamadas devem vir da mesma thread (no plugin, a EDT).</p>
|
||||
*/
|
||||
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<String> selfName;
|
||||
private final Consumer<DamasMessage> link;
|
||||
private final Listener listener;
|
||||
|
||||
private final List<Pending> pending = new ArrayList<>();
|
||||
private final Set<String> processed = new HashSet<>();
|
||||
private Set<String> 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<String> selfName,
|
||||
Consumer<DamasMessage> 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<Integer> 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<Pending> 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<String> peerIds) {
|
||||
Set<String> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.</p>
|
||||
*
|
||||
* <p>Empate após 20 lances de cada lado só com damas, sem captura nem movimento de pedra.</p>
|
||||
*/
|
||||
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<Move> 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<Move> 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<Integer> 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<Move> computeLegalMoves() {
|
||||
List<Move> 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<Integer> path = new ArrayList<>(List.of(square));
|
||||
collectCaptures(square, piece, path, new ArrayList<>(), captures);
|
||||
board[square] = piece;
|
||||
}
|
||||
}
|
||||
if (!captures.isEmpty()) {
|
||||
return keepLargestCaptures(captures);
|
||||
}
|
||||
List<Move> 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<Move> keepLargestCaptures(List<Move> captures) {
|
||||
int largest = 0;
|
||||
for (Move move : captures) {
|
||||
largest = Math.max(largest, move.captured().size());
|
||||
}
|
||||
List<Move> 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<Integer> path,
|
||||
List<Integer> captured,
|
||||
List<Move> 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<Integer> 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<Move> 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;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package pitiupi.damas.game;
|
||||
|
||||
public enum GameResult {
|
||||
IN_PROGRESS,
|
||||
WHITE_WINS,
|
||||
BLACK_WINS,
|
||||
DRAW
|
||||
}
|
||||
@@ -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<Integer> path, List<Integer> 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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<Integer> 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<Integer> getPath() {
|
||||
return path == null ? null : java.util.Arrays.stream(path).boxed().toList();
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<Class<? extends Message>> 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";
|
||||
}
|
||||
}
|
||||
@@ -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<DamasMessage> 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<Move> 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));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
Reference in new issue
Block a user