views = connectionManager.getPresenceService().listPeerViews();
- peerModel.clear();
- for (UserPeerView view : views) {
- if (!view.isBroadcastTarget() && !view.isSelf()) {
- peerModel.addElement(new PeerItem(view.getInstanceId(), view.getDisplayName()));
- }
- }
- if (selected != null && peerModel.contains(selected)) {
- peerList.setSelectedValue(selected, false);
- }
- updateInviteButton();
- }
-
- private void updateInviteButton() {
- inviteButton.setEnabled(peerList.getSelectedValue() != null && controller.canInvite());
- }
-
- private static JButton button(String text, Runnable action) {
- JButton button = new JButton(text);
- button.addActionListener(e -> action.run());
- return button;
- }
-
- private static JLabel titleLabel(String text) {
- JLabel label = new JLabel(text);
- label.setFont(label.getFont().deriveFont(Font.BOLD));
- return label;
- }
-
- private static JPanel stackedCard(String title, JComponent... rows) {
- JPanel stack = new JPanel();
- stack.setLayout(new BoxLayout(stack, BoxLayout.Y_AXIS));
- JLabel titleLabel = titleLabel(title);
- titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
- stack.add(titleLabel);
- for (JComponent row : rows) {
- stack.add(Box.createVerticalStrut(8));
- row.setAlignmentX(Component.LEFT_ALIGNMENT);
- if (row instanceof JButton) {
- row.setMaximumSize(new Dimension(Integer.MAX_VALUE, row.getPreferredSize().height));
- }
- stack.add(row);
- }
- JPanel card = new JPanel(new BorderLayout());
- card.add(stack, BorderLayout.NORTH);
- return card;
- }
-
- /** Texto com quebra de linha sem HTML, pois inclui nomes vindos da rede. */
- private static JTextArea wrappedText() {
- JTextArea area = new JTextArea();
- // O Nimbus pinta fundo e borda de campo de texto mesmo com setOpaque(false).
- area.setUI(new BasicTextAreaUI());
- area.setEditable(false);
- area.setFocusable(false);
- area.setOpaque(false);
- area.setBorder(null);
- area.setForeground(UIManager.getColor("Label.foreground"));
- area.setLineWrap(true);
- area.setWrapStyleWord(true);
- area.setFont(UIManager.getFont("Label.font"));
- return area;
- }
-
- private record PeerItem(String id, String name) {
- @Override
- public String toString() {
- return name;
- }
- }
-}
diff --git a/plugins/damas/src/pitiupi/damas/control/DamasController.java b/plugins/damas/src/pitiupi/damas/control/DamasController.java
deleted file mode 100644
index ca20eca..0000000
--- a/plugins/damas/src/pitiupi/damas/control/DamasController.java
+++ /dev/null
@@ -1,422 +0,0 @@
-package pitiupi.damas.control;
-
-import pitiupi.damas.game.DamasGame;
-import pitiupi.damas.game.GameResult;
-import pitiupi.damas.game.Side;
-import pitiupi.damas.net.DamasMessage;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.ThreadLocalRandom;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-
-/**
- * Sessão de jogo: convites, lances e entrega confiável sobre UDP.
- *
- * Cada mensagem enviada fica pendente até chegar o ACK e é reenviada a cada {@link #tick()}.
- * O receptor confirma sempre, mesmo as duplicadas, e processa cada mensagem uma única vez.
- * Lances recebidos são validados pelas regras locais antes de serem aplicados.
- *
- * Não é thread-safe: todas as chamadas devem vir da mesma thread (no plugin, a EDT).
- */
-public final class DamasController {
-
- public enum Phase {
- LOBBY,
- INVITE_SENT,
- PLAYING,
- FINISHED
- }
-
- public interface Listener {
- void onStateChanged();
-
- /** Algo exige a atenção do jogador: convite recebido ou partida iniciada. */
- void onAttentionNeeded();
- }
-
- /** Convite recebido aguardando a resposta do jogador. */
- public record IncomingInvite(String gameId, String fromId, String fromName, Side inviterSide) {
- }
-
- static final int INVITE_MAX_ATTEMPTS = 20;
- static final int MESSAGE_MAX_ATTEMPTS = 120;
-
- private final String selfId;
- private final Supplier selfName;
- private final Consumer link;
- private final Listener listener;
-
- private final List pending = new ArrayList<>();
- private final Set processed = new HashSet<>();
- private Set knownPeers = Set.of();
- private int nextSeq = 1;
-
- private Phase phase = Phase.LOBBY;
- private String gameId;
- private String opponentId;
- private String opponentName;
- private Side mySide;
- private DamasGame game;
- private boolean opponentAway;
- private IncomingInvite incomingInvite;
- private String notice = "";
-
- public DamasController(
- String selfId,
- Supplier selfName,
- Consumer link,
- Listener listener
- ) {
- this.selfId = selfId;
- this.selfName = selfName;
- this.link = link;
- this.listener = listener;
- }
-
- public Phase getPhase() {
- return phase;
- }
-
- public DamasGame getGame() {
- return game;
- }
-
- public Side getMySide() {
- return mySide;
- }
-
- public String getOpponentId() {
- return opponentId;
- }
-
- public String getOpponentName() {
- return opponentName;
- }
-
- public boolean isOpponentAway() {
- return opponentAway;
- }
-
- public IncomingInvite getIncomingInvite() {
- return incomingInvite;
- }
-
- /** Último aviso para o jogador (recusa, fim de partida, adversário saiu…). */
- public String getNotice() {
- return notice;
- }
-
- public boolean isMyTurn() {
- return phase == Phase.PLAYING && game.getTurn() == mySide;
- }
-
- public boolean canInvite() {
- return (phase == Phase.LOBBY || phase == Phase.FINISHED) && incomingInvite == null;
- }
-
- public boolean invite(String peerId, String peerName) {
- if (!canInvite()) {
- return false;
- }
- gameId = UUID.randomUUID().toString();
- opponentId = peerId;
- opponentName = peerName;
- mySide = ThreadLocalRandom.current().nextBoolean() ? Side.WHITE : Side.BLACK;
- game = null;
- opponentAway = false;
- phase = Phase.INVITE_SENT;
- notice = "";
- sendReliable(DamasMessage.invite(gameId, selfId, peerId, selfName.get(), nextSeq++, mySide));
- listener.onStateChanged();
- return true;
- }
-
- public void cancelInvite() {
- if (phase != Phase.INVITE_SENT) {
- return;
- }
- forgetCurrentGameMessages();
- sendControl(DamasMessage.Type.CANCEL);
- phase = Phase.LOBBY;
- notice = "";
- listener.onStateChanged();
- }
-
- public void acceptInvite() {
- IncomingInvite invite = incomingInvite;
- if (invite == null) {
- return;
- }
- incomingInvite = null;
- gameId = invite.gameId();
- opponentId = invite.fromId();
- opponentName = invite.fromName();
- mySide = invite.inviterSide().opposite();
- sendControl(DamasMessage.Type.ACCEPT);
- startGame();
- }
-
- public void declineInvite() {
- IncomingInvite invite = incomingInvite;
- if (invite == null) {
- return;
- }
- incomingInvite = null;
- sendReliable(DamasMessage.control(
- DamasMessage.Type.DECLINE, invite.gameId(), selfId, invite.fromId(), selfName.get(), nextSeq++));
- listener.onStateChanged();
- }
-
- /**
- * Joga o lance local.
- *
- * @return {@code false} se não for a vez do jogador ou o caminho não for legal.
- */
- public boolean play(List path) {
- if (!isMyTurn() || game.apply(path) == null) {
- return false;
- }
- sendReliable(DamasMessage.move(gameId, selfId, opponentId, selfName.get(), nextSeq++, path));
- finishIfGameOver();
- listener.onStateChanged();
- return true;
- }
-
- /** Desiste da partida ou, se o adversário saiu da rede, apenas a encerra. */
- public void resign() {
- if (phase != Phase.PLAYING) {
- return;
- }
- sendControl(DamasMessage.Type.RESIGN);
- phase = Phase.FINISHED;
- notice = opponentAway
- ? "Partida encerrada: " + opponentName + " saiu da rede."
- : "Você desistiu. " + opponentName + " venceu.";
- listener.onStateChanged();
- }
-
- public void backToLobby() {
- if (phase != Phase.FINISHED) {
- return;
- }
- phase = Phase.LOBBY;
- game = null;
- notice = "";
- listener.onStateChanged();
- }
-
- /** Reenvia o que ainda não foi confirmado. Chamar periodicamente. */
- public void tick() {
- boolean changed = false;
- for (Iterator it = pending.iterator(); it.hasNext(); ) {
- Pending item = it.next();
- if (item.attempts >= maxAttempts(item.message)) {
- it.remove();
- if (item.message.getType() == DamasMessage.Type.INVITE && isCurrentGame(item.message)
- && phase == Phase.INVITE_SENT) {
- phase = Phase.LOBBY;
- notice = opponentName + " não respondeu ao convite.";
- changed = true;
- }
- continue;
- }
- item.attempts++;
- link.accept(item.message);
- }
- if (changed) {
- listener.onStateChanged();
- }
- }
-
- /** Atualiza a presença. O adversário que sumir pode voltar (ex.: falha rápida no Wi-Fi). */
- public void onPeersChanged(Set peerIds) {
- Set previous = knownPeers;
- knownPeers = Set.copyOf(peerIds);
- boolean changed = false;
-
- if (incomingInvite != null && previous.contains(incomingInvite.fromId())
- && !peerIds.contains(incomingInvite.fromId())) {
- notice = incomingInvite.fromName() + " saiu da rede; convite cancelado.";
- incomingInvite = null;
- changed = true;
- }
- if (phase == Phase.INVITE_SENT && previous.contains(opponentId) && !peerIds.contains(opponentId)) {
- forgetCurrentGameMessages();
- phase = Phase.LOBBY;
- notice = opponentName + " saiu da rede; convite cancelado.";
- changed = true;
- }
- if (phase == Phase.PLAYING) {
- boolean away = previous.contains(opponentId) && !peerIds.contains(opponentId)
- || opponentAway && !peerIds.contains(opponentId);
- if (away != opponentAway) {
- opponentAway = away;
- changed = true;
- }
- }
- if (changed) {
- listener.onStateChanged();
- }
- }
-
- public void receive(DamasMessage message) {
- if (!selfId.equals(message.getTo()) || message.getFrom() == null || message.getGameId() == null) {
- return;
- }
- if (message.getType() == DamasMessage.Type.ACK) {
- pending.removeIf(item -> item.message.getSeq() == message.getSeq()
- && item.message.getGameId().equals(message.getGameId())
- && item.message.getTo().equals(message.getFrom()));
- return;
- }
- link.accept(DamasMessage.ack(message, selfId));
- String key = message.getFrom() + "|" + message.getGameId() + "|" + message.getSeq();
- if (!processed.add(key)) {
- return;
- }
- switch (message.getType()) {
- case INVITE -> onInvite(message);
- case ACCEPT -> onAccept(message);
- case DECLINE -> onInviteRefused(message, " recusou o convite.");
- case BUSY -> onInviteRefused(message, " está ocupado no momento.");
- case CANCEL -> onCancel(message);
- case MOVE -> onMove(message);
- case RESIGN -> onResign(message);
- default -> {
- }
- }
- }
-
- private void onInvite(DamasMessage message) {
- if (message.getInviterSide() == null) {
- return;
- }
- if (!canInvite()) {
- sendReliable(DamasMessage.control(
- DamasMessage.Type.BUSY, message.getGameId(), selfId, message.getFrom(), selfName.get(), nextSeq++));
- return;
- }
- incomingInvite = new IncomingInvite(
- message.getGameId(), message.getFrom(), message.getFromName(), message.getInviterSide());
- listener.onStateChanged();
- listener.onAttentionNeeded();
- }
-
- private void onAccept(DamasMessage message) {
- if (phase == Phase.INVITE_SENT && isFromOpponent(message)) {
- startGame();
- }
- }
-
- private void onInviteRefused(DamasMessage message, String reason) {
- if (phase == Phase.INVITE_SENT && isFromOpponent(message)) {
- phase = Phase.LOBBY;
- notice = opponentName + reason;
- listener.onStateChanged();
- }
- }
-
- private void onCancel(DamasMessage message) {
- if (incomingInvite != null && incomingInvite.gameId().equals(message.getGameId())) {
- notice = incomingInvite.fromName() + " cancelou o convite.";
- incomingInvite = null;
- listener.onStateChanged();
- } else if (phase == Phase.PLAYING && isFromOpponent(message)) {
- // O convite foi cancelado enquanto o aceite estava a caminho.
- phase = Phase.LOBBY;
- game = null;
- notice = opponentName + " cancelou o convite.";
- listener.onStateChanged();
- }
- }
-
- private void onMove(DamasMessage message) {
- if (phase != Phase.PLAYING || !isFromOpponent(message) || message.getPath() == null || isMyTurn()) {
- return;
- }
- if (game.apply(message.getPath()) == null) {
- phase = Phase.FINISHED;
- notice = "Partida interrompida: lance inválido recebido de " + opponentName + ".";
- } else {
- finishIfGameOver();
- }
- listener.onStateChanged();
- }
-
- private void onResign(DamasMessage message) {
- if (phase == Phase.PLAYING && isFromOpponent(message)) {
- phase = Phase.FINISHED;
- notice = opponentName + " desistiu. Você venceu!";
- listener.onStateChanged();
- }
- }
-
- private void startGame() {
- game = new DamasGame();
- phase = Phase.PLAYING;
- opponentAway = false;
- notice = "";
- listener.onStateChanged();
- listener.onAttentionNeeded();
- }
-
- private void finishIfGameOver() {
- GameResult result = game.getResult();
- if (result == GameResult.IN_PROGRESS) {
- return;
- }
- phase = Phase.FINISHED;
- if (result == GameResult.DRAW) {
- notice = "Empate: 20 lances de cada lado só com damas, sem captura.";
- } else {
- Side winner = result == GameResult.WHITE_WINS ? Side.WHITE : Side.BLACK;
- notice = winner == mySide ? "Você venceu!" : opponentName + " venceu.";
- }
- }
-
- private boolean isFromOpponent(DamasMessage message) {
- return isCurrentGame(message) && message.getFrom().equals(opponentId);
- }
-
- private boolean isCurrentGame(DamasMessage message) {
- return message.getGameId().equals(gameId);
- }
-
- /** Um lance da partida em curso nunca é descartado: o adversário pode voltar à rede. */
- private int maxAttempts(DamasMessage message) {
- return switch (message.getType()) {
- case INVITE -> INVITE_MAX_ATTEMPTS;
- case MOVE -> phase == Phase.PLAYING && isCurrentGame(message) ? Integer.MAX_VALUE : MESSAGE_MAX_ATTEMPTS;
- default -> MESSAGE_MAX_ATTEMPTS;
- };
- }
-
- /** Preserva o que ainda está a caminho de partidas anteriores, como o lance final. */
- private void forgetCurrentGameMessages() {
- pending.removeIf(item -> isCurrentGame(item.message));
- }
-
- private void sendControl(DamasMessage.Type type) {
- sendReliable(DamasMessage.control(type, gameId, selfId, opponentId, selfName.get(), nextSeq++));
- }
-
- private void sendReliable(DamasMessage message) {
- pending.add(new Pending(message));
- link.accept(message);
- }
-
- private static final class Pending {
- private final DamasMessage message;
- private int attempts;
-
- private Pending(DamasMessage message) {
- this.message = message;
- }
- }
-}
diff --git a/plugins/damas/src/pitiupi/damas/game/DamasGame.java b/plugins/damas/src/pitiupi/damas/game/DamasGame.java
deleted file mode 100644
index 591f07a..0000000
--- a/plugins/damas/src/pitiupi/damas/game/DamasGame.java
+++ /dev/null
@@ -1,271 +0,0 @@
-package pitiupi.damas.game;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Regras do jogo de damas brasileiro (tabuleiro 8×8), sem rede nem Swing.
- *
- * Pedras andam uma casa para a frente e capturam para a frente e para trás. Damas são
- * voadoras. A captura é obrigatória e vale a lei da maioria: só são legais as sequências com
- * o maior número de peças; em caso de igualdade, a escolha é livre. As peças capturadas só
- * saem do tabuleiro no fim da sequência e não podem ser saltadas duas vezes. A pedra que
- * passa pela última linha no meio de uma captura só é promovida se terminar nela.
- *
- * Empate após 20 lances de cada lado só com damas, sem captura nem movimento de pedra.
- */
-public final class DamasGame {
-
- public static final int SIZE = 8;
- private static final int INITIAL_ROWS = 3;
- private static final int DRAW_QUIET_PLIES = 40;
- private static final int[][] DIRECTIONS = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}};
-
- private final Piece[] board = new Piece[SIZE * SIZE];
- private Side turn = Side.WHITE;
- private int quietPlies;
- private GameResult result = GameResult.IN_PROGRESS;
- private Move lastMove;
- private List legalMoves;
-
- public DamasGame() {
- for (int row = 0; row < SIZE; row++) {
- for (int col = 0; col < SIZE; col++) {
- if (!isDarkSquare(row, col)) {
- continue;
- }
- if (row < INITIAL_ROWS) {
- board[square(row, col)] = Piece.BLACK_MAN;
- } else if (row >= SIZE - INITIAL_ROWS) {
- board[square(row, col)] = Piece.WHITE_MAN;
- }
- }
- }
- legalMoves = computeLegalMoves();
- }
-
- /**
- * Posição arbitrária para testes: uma string por linha, com {@code w b W B} e {@code .}.
- */
- static DamasGame fromRows(Side turn, String... rows) {
- DamasGame game = new DamasGame();
- for (int row = 0; row < SIZE; row++) {
- for (int col = 0; col < SIZE; col++) {
- game.board[square(row, col)] = switch (rows[row].charAt(col)) {
- case 'w' -> Piece.WHITE_MAN;
- case 'W' -> Piece.WHITE_KING;
- case 'b' -> Piece.BLACK_MAN;
- case 'B' -> Piece.BLACK_KING;
- default -> null;
- };
- }
- }
- game.turn = turn;
- game.legalMoves = game.computeLegalMoves();
- return game;
- }
-
- public static int square(int row, int col) {
- return row * SIZE + col;
- }
-
- public static int rowOf(int square) {
- return square / SIZE;
- }
-
- public static int colOf(int square) {
- return square % SIZE;
- }
-
- /** A casa escura fica no canto inferior esquerdo de cada jogador. */
- public static boolean isDarkSquare(int row, int col) {
- return (row + col) % 2 == 1;
- }
-
- public Piece pieceAt(int square) {
- return board[square];
- }
-
- public Side getTurn() {
- return turn;
- }
-
- public GameResult getResult() {
- return result;
- }
-
- public Move getLastMove() {
- return lastMove;
- }
-
- public List getLegalMoves() {
- return legalMoves;
- }
-
- public int countPieces(Side side) {
- int count = 0;
- for (Piece piece : board) {
- if (piece != null && piece.getSide() == side) {
- count++;
- }
- }
- return count;
- }
-
- /**
- * Aplica o lance com este caminho.
- *
- * @return o lance aplicado ou {@code null} se o caminho não for legal nesta posição.
- */
- public Move apply(List path) {
- if (result != GameResult.IN_PROGRESS) {
- return null;
- }
- for (Move move : legalMoves) {
- if (move.path().equals(path)) {
- applyLegal(move);
- return move;
- }
- }
- return null;
- }
-
- private void applyLegal(Move move) {
- Piece piece = board[move.from()];
- board[move.from()] = null;
- for (int captured : move.captured()) {
- board[captured] = null;
- }
- boolean promotes = !piece.isKing() && rowOf(move.to()) == piece.getSide().getPromotionRow();
- board[move.to()] = promotes ? piece.promoted() : piece;
-
- quietPlies = piece.isKing() && move.captured().isEmpty() ? quietPlies + 1 : 0;
- lastMove = move;
- Side mover = turn;
- turn = mover.opposite();
- legalMoves = computeLegalMoves();
-
- if (legalMoves.isEmpty()) {
- result = mover == Side.WHITE ? GameResult.WHITE_WINS : GameResult.BLACK_WINS;
- } else if (quietPlies >= DRAW_QUIET_PLIES) {
- result = GameResult.DRAW;
- }
- }
-
- private List computeLegalMoves() {
- List captures = new ArrayList<>();
- for (int square = 0; square < board.length; square++) {
- Piece piece = board[square];
- if (piece != null && piece.getSide() == turn) {
- // A peça em movimento não bloqueia o próprio caminho durante a sequência.
- board[square] = null;
- List path = new ArrayList<>(List.of(square));
- collectCaptures(square, piece, path, new ArrayList<>(), captures);
- board[square] = piece;
- }
- }
- if (!captures.isEmpty()) {
- return keepLargestCaptures(captures);
- }
- List moves = new ArrayList<>();
- for (int square = 0; square < board.length; square++) {
- Piece piece = board[square];
- if (piece != null && piece.getSide() == turn) {
- collectSimpleMoves(square, piece, moves);
- }
- }
- return moves;
- }
-
- private static List keepLargestCaptures(List captures) {
- int largest = 0;
- for (Move move : captures) {
- largest = Math.max(largest, move.captured().size());
- }
- List kept = new ArrayList<>();
- for (Move move : captures) {
- if (move.captured().size() == largest) {
- kept.add(move);
- }
- }
- return kept;
- }
-
- private void collectCaptures(
- int from,
- Piece piece,
- List path,
- List captured,
- List out
- ) {
- boolean extended = false;
- for (int[] direction : DIRECTIONS) {
- int victim = findVictim(from, direction, piece, captured);
- if (victim < 0) {
- continue;
- }
- int row = rowOf(victim) + direction[0];
- int col = colOf(victim) + direction[1];
- while (isOnBoard(row, col) && board[square(row, col)] == null) {
- extended = true;
- path.add(square(row, col));
- captured.add(victim);
- collectCaptures(square(row, col), piece, path, captured, out);
- captured.remove(captured.size() - 1);
- path.remove(path.size() - 1);
- if (!piece.isKing()) {
- break;
- }
- row += direction[0];
- col += direction[1];
- }
- }
- if (!extended && !captured.isEmpty()) {
- out.add(new Move(path, captured));
- }
- }
-
- /**
- * Primeira peça encontrada na direção, se puder ser capturada; {@code -1} caso contrário.
- * Peças já capturadas seguem no tabuleiro e bloqueiam a passagem.
- */
- private int findVictim(int from, int[] direction, Piece piece, List captured) {
- int row = rowOf(from) + direction[0];
- int col = colOf(from) + direction[1];
- while (isOnBoard(row, col)) {
- Piece found = board[square(row, col)];
- if (found != null) {
- boolean capturable = found.getSide() != piece.getSide() && !captured.contains(square(row, col));
- return capturable ? square(row, col) : -1;
- }
- if (!piece.isKing()) {
- return -1;
- }
- row += direction[0];
- col += direction[1];
- }
- return -1;
- }
-
- private void collectSimpleMoves(int from, Piece piece, List out) {
- for (int[] direction : DIRECTIONS) {
- if (!piece.isKing() && direction[0] != piece.getSide().getForwardRow()) {
- continue;
- }
- int row = rowOf(from) + direction[0];
- int col = colOf(from) + direction[1];
- while (isOnBoard(row, col) && board[square(row, col)] == null) {
- out.add(new Move(List.of(from, square(row, col)), List.of()));
- if (!piece.isKing()) {
- break;
- }
- row += direction[0];
- col += direction[1];
- }
- }
- }
-
- private static boolean isOnBoard(int row, int col) {
- return row >= 0 && row < SIZE && col >= 0 && col < SIZE;
- }
-}
diff --git a/plugins/damas/src/pitiupi/damas/game/GameResult.java b/plugins/damas/src/pitiupi/damas/game/GameResult.java
deleted file mode 100644
index 5ed26e6..0000000
--- a/plugins/damas/src/pitiupi/damas/game/GameResult.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package pitiupi.damas.game;
-
-public enum GameResult {
- IN_PROGRESS,
- WHITE_WINS,
- BLACK_WINS,
- DRAW
-}
diff --git a/plugins/damas/src/pitiupi/damas/game/Move.java b/plugins/damas/src/pitiupi/damas/game/Move.java
deleted file mode 100644
index 5070162..0000000
--- a/plugins/damas/src/pitiupi/damas/game/Move.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package pitiupi.damas.game;
-
-import java.util.List;
-
-/**
- * Lance completo: casas percorridas (origem, pousos) e peças capturadas, na ordem do salto.
- */
-public record Move(List path, List captured) {
-
- public Move {
- path = List.copyOf(path);
- captured = List.copyOf(captured);
- }
-
- public int from() {
- return path.get(0);
- }
-
- public int to() {
- return path.get(path.size() - 1);
- }
-}
diff --git a/plugins/damas/src/pitiupi/damas/game/Piece.java b/plugins/damas/src/pitiupi/damas/game/Piece.java
deleted file mode 100644
index f9afc2f..0000000
--- a/plugins/damas/src/pitiupi/damas/game/Piece.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package pitiupi.damas.game;
-
-public enum Piece {
- WHITE_MAN(Side.WHITE, false),
- WHITE_KING(Side.WHITE, true),
- BLACK_MAN(Side.BLACK, false),
- BLACK_KING(Side.BLACK, true);
-
- private final Side side;
- private final boolean king;
-
- Piece(Side side, boolean king) {
- this.side = side;
- this.king = king;
- }
-
- public Side getSide() {
- return side;
- }
-
- public boolean isKing() {
- return king;
- }
-
- public Piece promoted() {
- return side == Side.WHITE ? WHITE_KING : BLACK_KING;
- }
-}
diff --git a/plugins/damas/src/pitiupi/damas/game/Side.java b/plugins/damas/src/pitiupi/damas/game/Side.java
deleted file mode 100644
index c5dfa8e..0000000
--- a/plugins/damas/src/pitiupi/damas/game/Side.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package pitiupi.damas.game;
-
-/**
- * Lado de um jogador. As brancas começam e sobem o tabuleiro (linha 7 → linha 0).
- */
-public enum Side {
- WHITE("brancas", -1, 0),
- BLACK("pretas", 1, 7);
-
- private final String label;
- private final int forwardRow;
- private final int promotionRow;
-
- Side(String label, int forwardRow, int promotionRow) {
- this.label = label;
- this.forwardRow = forwardRow;
- this.promotionRow = promotionRow;
- }
-
- public String getLabel() {
- return label;
- }
-
- public int getForwardRow() {
- return forwardRow;
- }
-
- public int getPromotionRow() {
- return promotionRow;
- }
-
- public Side opposite() {
- return this == WHITE ? BLACK : WHITE;
- }
-}
diff --git a/plugins/damas/src/pitiupi/damas/net/DamasMessage.java b/plugins/damas/src/pitiupi/damas/net/DamasMessage.java
deleted file mode 100644
index a0014d9..0000000
--- a/plugins/damas/src/pitiupi/damas/net/DamasMessage.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package pitiupi.damas.net;
-
-import pitiupi.damas.game.Side;
-import pitiupi.models.Messages.Message;
-
-import java.util.List;
-
-/**
- * Mensagem do protocolo de damas. Viaja em UDP multicast: {@code to} indica o destinatário e os
- * demais peers a ignoram. Exceto {@link Type#ACK}, toda mensagem é confirmada e retransmitida.
- */
-public class DamasMessage extends Message {
-
- private static final long serialVersionUID = 1L;
-
- public enum Type {
- INVITE,
- ACCEPT,
- DECLINE,
- BUSY,
- CANCEL,
- MOVE,
- RESIGN,
- ACK
- }
-
- private final Type type;
- private final String gameId;
- private final String from;
- private final String to;
- private final String fromName;
- private final int seq;
- private final Side inviterSide;
- private final int[] path;
-
- private DamasMessage(
- Type type,
- String gameId,
- String from,
- String to,
- String fromName,
- int seq,
- Side inviterSide,
- int[] path
- ) {
- this.type = type;
- this.gameId = gameId;
- this.from = from;
- this.to = to;
- this.fromName = fromName;
- this.seq = seq;
- this.inviterSide = inviterSide;
- this.path = path;
- }
-
- public static DamasMessage invite(String gameId, String from, String to, String fromName, int seq, Side inviterSide) {
- return new DamasMessage(Type.INVITE, gameId, from, to, fromName, seq, inviterSide, null);
- }
-
- public static DamasMessage move(String gameId, String from, String to, String fromName, int seq, List path) {
- int[] squares = path.stream().mapToInt(Integer::intValue).toArray();
- return new DamasMessage(Type.MOVE, gameId, from, to, fromName, seq, null, squares);
- }
-
- /** ACCEPT, DECLINE, BUSY, CANCEL ou RESIGN. */
- public static DamasMessage control(Type type, String gameId, String from, String to, String fromName, int seq) {
- return new DamasMessage(type, gameId, from, to, fromName, seq, null, null);
- }
-
- public static DamasMessage ack(DamasMessage received, String from) {
- return new DamasMessage(Type.ACK, received.gameId, from, received.from, null, received.seq, null, null);
- }
-
- public Type getType() {
- return type;
- }
-
- public String getGameId() {
- return gameId;
- }
-
- public String getFrom() {
- return from;
- }
-
- public String getTo() {
- return to;
- }
-
- public String getFromName() {
- return fromName;
- }
-
- public int getSeq() {
- return seq;
- }
-
- public Side getInviterSide() {
- return inviterSide;
- }
-
- /** Caminho do lance ou {@code null} se a mensagem não for {@link Type#MOVE}. */
- public List getPath() {
- return path == null ? null : java.util.Arrays.stream(path).boxed().toList();
- }
-}
diff --git a/plugins/damas/src/pitiupi/damas/plugin/DamasPlugin.java b/plugins/damas/src/pitiupi/damas/plugin/DamasPlugin.java
deleted file mode 100644
index 5a01046..0000000
--- a/plugins/damas/src/pitiupi/damas/plugin/DamasPlugin.java
+++ /dev/null
@@ -1,162 +0,0 @@
-package pitiupi.damas.plugin;
-
-import pitiupi.api.plugin.PeerActionsRegistrar;
-import pitiupi.api.plugin.PluginWorkspace;
-import pitiupi.application.messaging.MessageDispatcher;
-import pitiupi.application.messaging.SendTarget;
-import pitiupi.application.messaging.TransportMode;
-import pitiupi.application.peeractions.PeerAction;
-import pitiupi.application.peeractions.PeerActionTarget;
-import pitiupi.application.peeractions.PeerTarget;
-import pitiupi.control.ConnectionManager;
-import pitiupi.damas.GUI.DamasPanel;
-import pitiupi.damas.control.DamasController;
-import pitiupi.damas.net.DamasMessage;
-import pitiupi.models.Messages.Message;
-import pitiupi.models.Plugin;
-import pitiupi.models.User;
-
-import javax.swing.SwingUtilities;
-import javax.swing.Timer;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-public class DamasPlugin extends Plugin {
-
- private static final int RESEND_INTERVAL_MS = 500;
-
- private ConnectionManager connectionManager;
- private PluginWorkspace workspace;
- private DamasController controller;
- private DamasPanel panel;
-
- @Override
- public void createPlugin(ConnectionManager connectionManager, PluginWorkspace workspace) {
- this.connectionManager = connectionManager;
- this.workspace = workspace;
- this.controller = new DamasController(
- connectionManager.getHeartbeatManager().getInstanceId(),
- connectionManager::getUserName,
- this::send,
- new DamasController.Listener() {
- @Override
- public void onStateChanged() {
- panel.refresh();
- updateStatusBar();
- }
-
- @Override
- public void onAttentionNeeded() {
- openTab();
- }
- }
- );
- this.panel = new DamasPanel(controller, connectionManager);
- bindShellWorkspaceContent(panel);
- installPeerActions(workspace.peerActions());
-
- connectionManager.addPeerListener(peers -> {
- Set ids = peers.stream().map(User::getInstanceId).collect(Collectors.toSet());
- SwingUtilities.invokeLater(() -> {
- controller.onPeersChanged(ids);
- panel.refreshPeers();
- });
- });
- new Timer(RESEND_INTERVAL_MS, e -> controller.tick()).start();
- }
-
- @Override
- public void installPeerActions(PeerActionsRegistrar registrar) {
- registrar.register(PeerAction.of(
- "damas.open",
- "Abrir damas",
- PeerActionTarget.ALL_PEERS,
- target -> openTab()
- ));
- registrar.register(PeerAction.of(
- "damas.invite",
- "Convidar para uma partida",
- PeerActionTarget.SINGLE_PEER,
- this::inviteFromPeerList
- ));
- }
-
- private void inviteFromPeerList(PeerTarget target) {
- openTab();
- if (target instanceof PeerTarget.Single single) {
- controller.invite(single.peer().getInstanceId(), single.peer().getDisplayName());
- }
- }
-
- private void openTab() {
- workspace.openOrFocusTab(getIdentifier(), getDisplayName());
- }
-
- /** Com a aba fechada, a barra de status é o que avisa sobre convite e vez de jogar. */
- private void updateStatusBar() {
- String text = statusBarText();
- if (text != null) {
- workspace.setStatusMessage(text);
- }
- }
-
- private String statusBarText() {
- if (controller.getIncomingInvite() != null) {
- return "Damas: " + controller.getIncomingInvite().fromName() + " convidou você para uma partida";
- }
- return switch (controller.getPhase()) {
- case LOBBY -> null;
- case INVITE_SENT -> "Damas: aguardando resposta de " + controller.getOpponentName();
- case PLAYING -> controller.isMyTurn()
- ? "Damas: sua vez contra " + controller.getOpponentName()
- : "Damas: vez de " + controller.getOpponentName();
- case FINISHED -> "Damas: " + controller.getNotice();
- };
- }
-
- /**
- * Multicast é o único transporte que funciona sempre que o peer aparece na lista, pois é
- * o caminho do heartbeat. A entrega confiável fica a cargo do {@link DamasController}.
- */
- private void send(DamasMessage message) {
- MessageDispatcher.send(connectionManager, message, SendTarget.broadcastAll(), TransportMode.MULTICAST_UDP);
- }
-
- @Override
- public List> getMessages() {
- return List.of(DamasMessage.class);
- }
-
- @Override
- public void receiveMessage(Message message) {
- if (message instanceof DamasMessage damasMessage) {
- SwingUtilities.invokeLater(() -> controller.receive(damasMessage));
- }
- }
-
- @Override
- public String getName() {
- return "Damas";
- }
-
- @Override
- public String getDisplayName() {
- return "Damas";
- }
-
- @Override
- public String getAuthor() {
- return "Felipe Chaves";
- }
-
- @Override
- public String getVersion() {
- return "1";
- }
-
- @Override
- public String getIdentifier() {
- return "Pitiupi.Damas";
- }
-}
diff --git a/plugins/damas/test/pitiupi/damas/control/DamasControllerTest.java b/plugins/damas/test/pitiupi/damas/control/DamasControllerTest.java
deleted file mode 100644
index 54866c8..0000000
--- a/plugins/damas/test/pitiupi/damas/control/DamasControllerTest.java
+++ /dev/null
@@ -1,312 +0,0 @@
-package pitiupi.damas.control;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import pitiupi.damas.game.Move;
-import pitiupi.damas.game.Side;
-import pitiupi.damas.net.DamasMessage;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.util.ArrayDeque;
-import java.util.Deque;
-import java.util.List;
-import java.util.Random;
-import java.util.Set;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-class DamasControllerTest {
-
- /** Rede simulada em multicast: todos recebem tudo, inclusive o eco do próprio envio. */
- private final Deque wire = new ArrayDeque<>();
- private Random loss;
- private double lossRate;
- private int attentionA;
- private int attentionB;
- private DamasController a;
- private DamasController b;
- private DamasController c;
-
- @BeforeEach
- void setUp() {
- lossRate = 0;
- loss = new Random(42);
- a = controller("a", () -> attentionA++);
- b = controller("b", () -> attentionB++);
- c = controller("c", () -> { });
- }
-
- private DamasController controller(String id, Runnable onAttention) {
- return new DamasController(id, () -> id.toUpperCase(), wire::add, new DamasController.Listener() {
- @Override
- public void onStateChanged() {
- }
-
- @Override
- public void onAttentionNeeded() {
- onAttention.run();
- }
- });
- }
-
- /** Entrega o que está na rede, passando pela serialização real e descartando conforme a perda. */
- private void deliver() {
- for (int guard = 0; guard < 10_000 && !wire.isEmpty(); guard++) {
- DamasMessage message = wire.poll();
- for (DamasController target : List.of(a, b, c)) {
- if (loss.nextDouble() >= lossRate) {
- target.receive(roundTrip(message));
- }
- }
- }
- }
-
- private void settle() {
- deliver();
- for (int i = 0; i < 200; i++) {
- a.tick();
- b.tick();
- c.tick();
- deliver();
- }
- }
-
- private static DamasMessage roundTrip(DamasMessage message) {
- try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(message.toByteArray()))) {
- return (DamasMessage) in.readObject();
- } catch (IOException | ClassNotFoundException e) {
- throw new AssertionError(e);
- }
- }
-
- private void startGame() {
- assertTrue(a.invite("b", "B"));
- deliver();
- b.acceptInvite();
- deliver();
- }
-
- private DamasController whitePlayer() {
- return a.getMySide() == Side.WHITE ? a : b;
- }
-
- private DamasController blackPlayer() {
- return a.getMySide() == Side.WHITE ? b : a;
- }
-
- @Test
- void acceptedInviteStartsGameWithOppositeSides() {
- startGame();
- assertEquals(DamasController.Phase.PLAYING, a.getPhase());
- assertEquals(DamasController.Phase.PLAYING, b.getPhase());
- assertEquals(a.getMySide().opposite(), b.getMySide());
- assertEquals("B", a.getOpponentName());
- assertEquals("A", b.getOpponentName());
- assertTrue(attentionA > 0 && attentionB > 0);
- }
-
- @Test
- void thirdPeerIgnoresTheConversation() {
- startGame();
- assertEquals(DamasController.Phase.LOBBY, c.getPhase());
- assertNull(c.getIncomingInvite());
- }
-
- @Test
- void declinedInviteReturnsInviterToLobby() {
- a.invite("b", "B");
- deliver();
- b.declineInvite();
- deliver();
- assertEquals(DamasController.Phase.LOBBY, a.getPhase());
- assertEquals("B recusou o convite.", a.getNotice());
- assertNull(b.getIncomingInvite());
- }
-
- @Test
- void cancelledInviteDisappearsFromInvitee() {
- a.invite("b", "B");
- deliver();
- assertNotNull(b.getIncomingInvite());
- a.cancelInvite();
- deliver();
- assertNull(b.getIncomingInvite());
- }
-
- @Test
- void inviteWhileBusyIsAnsweredAutomatically() {
- startGame();
- assertTrue(c.invite("b", "B"));
- deliver();
- assertEquals(DamasController.Phase.LOBBY, c.getPhase());
- assertEquals("B está ocupado no momento.", c.getNotice());
- assertEquals(DamasController.Phase.PLAYING, b.getPhase());
- }
-
- @Test
- void movesReachOpponentAndAlternateTurns() {
- startGame();
- DamasController white = whitePlayer();
- DamasController black = blackPlayer();
- assertTrue(white.isMyTurn());
- assertFalse(black.isMyTurn());
- assertFalse(black.play(black.getGame().getLegalMoves().get(0).path()));
-
- Move move = white.getGame().getLegalMoves().get(0);
- assertTrue(white.play(move.path()));
- deliver();
- assertEquals(move, black.getGame().getLastMove());
- assertTrue(black.isMyTurn());
- }
-
- @Test
- void duplicatedMoveIsAppliedOnce() {
- startGame();
- DamasController white = whitePlayer();
- DamasController black = blackPlayer();
- white.play(white.getGame().getLegalMoves().get(0).path());
- DamasMessage sent = wire.peek();
- deliver();
- black.receive(sent);
- deliver();
- assertTrue(black.isMyTurn());
- assertEquals(DamasController.Phase.PLAYING, black.getPhase());
- }
-
- @Test
- void wholeGameStaysInSyncOverLossyNetwork() {
- lossRate = 0.4;
- a.invite("b", "B");
- settle();
- b.acceptInvite();
- settle();
- assertEquals(DamasController.Phase.PLAYING, a.getPhase());
-
- Random choice = new Random(7);
- for (int ply = 0; ply < 400 && a.getPhase() == DamasController.Phase.PLAYING; ply++) {
- DamasController mover = a.isMyTurn() ? a : b;
- assertTrue(mover.isMyTurn(), "um dos jogadores deve ter a vez");
- List moves = mover.getGame().getLegalMoves();
- assertTrue(mover.play(moves.get(choice.nextInt(moves.size())).path()));
- settle();
- assertEquals(a.getGame().getLastMove(), b.getGame().getLastMove());
- assertEquals(a.getGame().getTurn(), b.getGame().getTurn());
- assertEquals(a.getGame().getLegalMoves(), b.getGame().getLegalMoves());
- }
- assertEquals(a.getPhase(), b.getPhase());
- }
-
- @Test
- void unansweredInviteTimesOut() {
- lossRate = 1;
- a.invite("b", "B");
- for (int i = 0; i <= DamasController.INVITE_MAX_ATTEMPTS; i++) {
- a.tick();
- }
- assertEquals(DamasController.Phase.LOBBY, a.getPhase());
- assertEquals("B não respondeu ao convite.", a.getNotice());
- }
-
- @Test
- void illegalMoveFromOpponentEndsGameWithoutApplyingIt() {
- startGame();
- DamasController white = whitePlayer();
- DamasController black = blackPlayer();
- String blackId = black == a ? "a" : "b";
- String whiteId = white == a ? "a" : "b";
- String gameId = gameIdOf(white, whiteId, blackId);
- black.receive(DamasMessage.move(gameId, whiteId, blackId, "X", 999, List.of(0, 63)));
- assertEquals(DamasController.Phase.FINISHED, black.getPhase());
- assertEquals(12, black.getGame().countPieces(Side.WHITE));
- }
-
- private String gameIdOf(DamasController white, String whiteId, String blackId) {
- white.play(white.getGame().getLegalMoves().get(0).path());
- DamasMessage sent = wire.poll();
- wire.clear();
- return sent.getGameId();
- }
-
- @Test
- void forgedMoveFromThirdPeerIsIgnored() {
- startGame();
- DamasController black = blackPlayer();
- String blackId = black == a ? "a" : "b";
- DamasController white = whitePlayer();
- white.play(white.getGame().getLegalMoves().get(0).path());
- DamasMessage real = wire.poll();
- wire.clear();
- black.receive(DamasMessage.move(real.getGameId(), "c", blackId, "C", 1000, real.getPath()));
- assertFalse(black.isMyTurn());
- assertEquals(DamasController.Phase.PLAYING, black.getPhase());
- }
-
- @Test
- void resignFinishesBothSides() {
- startGame();
- a.resign();
- deliver();
- assertEquals(DamasController.Phase.FINISHED, a.getPhase());
- assertEquals(DamasController.Phase.FINISHED, b.getPhase());
- assertEquals("A desistiu. Você venceu!", b.getNotice());
- }
-
- @Test
- void opponentLeavingMarksAwayAndReturningClearsIt() {
- a.onPeersChanged(Set.of("b"));
- startGame();
- a.onPeersChanged(Set.of());
- assertTrue(a.isOpponentAway());
- assertEquals(DamasController.Phase.PLAYING, a.getPhase());
- a.onPeersChanged(Set.of("b"));
- assertFalse(a.isOpponentAway());
- }
-
- @Test
- void refusedRematchLeavesNoStaleBoard() {
- startGame();
- a.resign();
- deliver();
- a.invite("b", "B");
- deliver();
- b.declineInvite();
- deliver();
- assertEquals(DamasController.Phase.LOBBY, a.getPhase());
- assertNull(a.getGame());
- }
-
- @Test
- void cancellingRematchStillDeliversLastMessageOfPreviousGame() {
- startGame();
- lossRate = 1;
- a.resign();
- deliver();
- assertEquals(DamasController.Phase.PLAYING, b.getPhase());
- a.invite("c", "C");
- a.cancelInvite();
- lossRate = 0;
- settle();
- assertEquals(DamasController.Phase.FINISHED, b.getPhase());
- }
-
- @Test
- void rematchWorksAfterGameEnds() {
- startGame();
- a.resign();
- deliver();
- assertTrue(a.invite("b", "B"));
- deliver();
- assertNotNull(b.getIncomingInvite());
- b.acceptInvite();
- deliver();
- assertEquals(DamasController.Phase.PLAYING, a.getPhase());
- assertEquals(DamasController.Phase.PLAYING, b.getPhase());
- assertEquals(12, a.getGame().countPieces(Side.WHITE));
- }
-}
diff --git a/plugins/damas/test/pitiupi/damas/game/DamasGameTest.java b/plugins/damas/test/pitiupi/damas/game/DamasGameTest.java
deleted file mode 100644
index 051116e..0000000
--- a/plugins/damas/test/pitiupi/damas/game/DamasGameTest.java
+++ /dev/null
@@ -1,248 +0,0 @@
-package pitiupi.damas.game;
-
-import org.junit.jupiter.api.Test;
-
-import java.util.List;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-class DamasGameTest {
-
- private static int sq(int row, int col) {
- return DamasGame.square(row, col);
- }
-
- @Test
- void initialPositionHasTwelvePiecesAndSevenMovesForWhite() {
- DamasGame game = new DamasGame();
- assertEquals(12, game.countPieces(Side.WHITE));
- assertEquals(12, game.countPieces(Side.BLACK));
- assertEquals(Side.WHITE, game.getTurn());
- assertEquals(7, game.getLegalMoves().size());
- }
-
- @Test
- void lowerLeftCornerIsDarkForWhite() {
- assertTrue(DamasGame.isDarkSquare(7, 0));
- assertFalse(DamasGame.isDarkSquare(7, 7));
- }
-
- @Test
- void manCannotMoveBackwards() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "b.......",
- "........",
- "........",
- "...w....",
- "........",
- "........",
- "........");
- assertNull(game.apply(List.of(sq(4, 3), sq(5, 2))));
- assertNotNull(game.apply(List.of(sq(4, 3), sq(3, 2))));
- }
-
- @Test
- void captureIsMandatoryAndManCapturesBackwards() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "........",
- "........",
- "..w.....",
- "...b....",
- "........",
- ".w......",
- "........");
- assertEquals(1, game.getLegalMoves().size());
- assertNull(game.apply(List.of(sq(6, 1), sq(5, 0))));
- Move move = game.apply(List.of(sq(3, 2), sq(5, 4)));
- assertEquals(List.of(sq(4, 3)), move.captured());
- assertNull(game.pieceAt(sq(4, 3)));
- }
-
- @Test
- void majorityRuleForcesLongestSequence() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "........",
- "...b....",
- "........",
- "...b.b..",
- "....w...",
- "........",
- "........");
- assertEquals(1, game.getLegalMoves().size());
- assertEquals(List.of(sq(5, 4), sq(3, 2), sq(1, 4)), game.getLegalMoves().get(0).path());
- }
-
- @Test
- void capturedPiecesCannotBeJumpedTwiceAndOriginCountsAsEmpty() {
- // Ciclo de quatro saltos que termina na origem, sem repetir a primeira peça.
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "........",
- ".b.b....",
- "........",
- ".b.b....",
- "..w.....",
- "........",
- "........");
- assertEquals(2, game.getLegalMoves().size());
- Move move = game.apply(List.of(sq(5, 2), sq(3, 4), sq(1, 2), sq(3, 0), sq(5, 2)));
- assertEquals(4, move.captured().size());
- assertEquals(0, game.countPieces(Side.BLACK));
- }
-
- @Test
- void flyingKingMayLandOnAnySquareBehindTheCapturedPiece() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "........",
- "........",
- "........",
- "...b....",
- "........",
- ".W......",
- "........");
- assertEquals(4, game.getLegalMoves().size());
- for (Move move : game.getLegalMoves()) {
- assertEquals(List.of(sq(4, 3)), move.captured());
- }
- }
-
- @Test
- void flyingKingMovesAnyDistanceButNotOverOwnPieces() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "........",
- "........",
- "........",
- "........",
- "..w.....",
- "........",
- "W......b");
- assertNotNull(game.getLegalMoves().stream()
- .filter(m -> m.from() == sq(7, 0)).findAny().orElse(null));
- assertTrue(game.getLegalMoves().stream().noneMatch(m -> m.from() == sq(7, 0) && m.to() == sq(4, 3)));
-
- DamasGame open = DamasGame.fromRows(Side.WHITE,
- "........",
- "........",
- "........",
- "........",
- "........",
- "........",
- "........",
- "W......b");
- assertNotNull(open.apply(List.of(sq(7, 0), sq(0, 7))));
- }
-
- @Test
- void manReachingLastRowPromotes() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "..w.....",
- "........",
- "........",
- "........",
- "........",
- "........",
- "b.......");
- game.apply(List.of(sq(1, 2), sq(0, 1)));
- assertEquals(Piece.WHITE_KING, game.pieceAt(sq(0, 1)));
- }
-
- @Test
- void manPassingLastRowDuringCaptureDoesNotPromote() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "..b.b...",
- ".w......",
- "........",
- "........",
- "........",
- "........",
- "...b....");
- Move move = game.getLegalMoves().get(0);
- assertEquals(List.of(sq(2, 1), sq(0, 3), sq(2, 5)), move.path());
- game.apply(move.path());
- assertEquals(Piece.WHITE_MAN, game.pieceAt(sq(2, 5)));
- }
-
- @Test
- void playerWithoutMovesLoses() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- "........",
- "..b.....",
- ".w......",
- "........",
- "........",
- "........",
- "........",
- "........");
- game.apply(List.of(sq(2, 1), sq(0, 3)));
- assertEquals(GameResult.WHITE_WINS, game.getResult());
- assertTrue(game.getLegalMoves().isEmpty());
- assertNull(game.apply(List.of(sq(0, 3), sq(1, 2))));
- }
-
- @Test
- void twentyQuietKingMovesEachIsADraw() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- ".B......",
- "........",
- "........",
- "........",
- "........",
- "........",
- "........",
- "W.......");
- int[][] whiteSquares = {{7, 0}, {6, 1}};
- int[][] blackSquares = {{0, 1}, {1, 0}};
- for (int ply = 0; ply < 40; ply++) {
- assertEquals(GameResult.IN_PROGRESS, game.getResult());
- int[][] squares = ply % 2 == 0 ? whiteSquares : blackSquares;
- int[] from = squares[ply % 4 < 2 ? 0 : 1];
- int[] to = squares[ply % 4 < 2 ? 1 : 0];
- assertNotNull(game.apply(List.of(sq(from[0], from[1]), sq(to[0], to[1]))));
- }
- assertEquals(GameResult.DRAW, game.getResult());
- }
-
- @Test
- void manMoveResetsTheDrawCount() {
- DamasGame game = DamasGame.fromRows(Side.WHITE,
- ".B......",
- "........",
- "........",
- "........",
- "........",
- "w.......",
- "........",
- "..W.....");
- for (int ply = 0; ply < 38; ply++) {
- boolean out = ply % 4 < 2;
- if (ply % 2 == 0) {
- game.apply(out ? List.of(sq(7, 2), sq(6, 3)) : List.of(sq(6, 3), sq(7, 2)));
- } else {
- game.apply(out ? List.of(sq(0, 1), sq(1, 2)) : List.of(sq(1, 2), sq(0, 1)));
- }
- }
- assertNotNull(game.apply(List.of(sq(5, 0), sq(4, 1))));
- // Sem zerar, estes dois lances de dama completariam os 40 e dariam empate.
- assertNotNull(game.apply(List.of(sq(1, 2), sq(0, 1))));
- assertNotNull(game.apply(List.of(sq(6, 3), sq(7, 2))));
- assertEquals(GameResult.IN_PROGRESS, game.getResult());
- }
-
- @Test
- void illegalPathIsRejectedWithoutChangingTurn() {
- DamasGame game = new DamasGame();
- assertNull(game.apply(List.of(sq(5, 0), sq(3, 2))));
- assertEquals(Side.WHITE, game.getTurn());
- }
-}
diff --git a/scripts.zip b/scripts.zip
new file mode 100644
index 0000000..08c32a7
Binary files /dev/null and b/scripts.zip differ