Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static adg.util.BoardLogic.isPawnOnNest;
import static adg.util.BoardLogic.pawnIsOnNormalBoard;
import static com.adg.openapi.model.MoveResult.CAN_MAKE_MOVE;
import static com.adg.openapi.model.MoveType.MOVE;
import static com.adg.openapi.model.MoveType.SPLIT;
import static com.adg.openapi.model.MoveType.SWITCH;
import static com.adg.openapi.model.TempMessageType.CHECK_MOVE;
Expand Down Expand Up @@ -161,6 +162,6 @@ private static boolean trySplit(

private static MoveResponse checkMoveResponse(
GameState gs, String playerId, Card card, Pawn pawn, int steps) {
return MoveChecks.checkMove(gs, playerId, card.getUuid(), pawn.getPawnId(), steps);
return MoveChecks.checkMove(gs, playerId, card.getUuid(), pawn.getPawnId(), steps, MOVE);
}
}
12 changes: 7 additions & 5 deletions backend/src/main/java/adg/processing/MoveChecks.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package adg.processing;

import static com.adg.openapi.model.MoveType.MOVE;
import static com.adg.openapi.model.TempMessageType.CHECK_MOVE;

import adg.keezen.GameState;
import com.adg.openapi.model.MoveRequest;
import com.adg.openapi.model.MoveResponse;
import com.adg.openapi.model.MoveType;
import com.adg.openapi.model.PawnId;

/** Shared non-mutating move look-aheads used by the move recommenders / availability checks. */
Expand All @@ -14,17 +14,19 @@ final class MoveChecks {
private MoveChecks() {}

/**
* Run a single pawn's MOVE through a CHECK_MOVE — no temp mutations on the shared game state — and
* return the resulting response, whose result tells whether the move is legal.
* Run a single pawn's move through a CHECK_MOVE — no temp mutations on the shared game state —
* and return the resulting response, whose result tells whether the move is legal.
* {@code moveType} says what the steps are: a whole card ({@code MOVE}) or one half of a 7-split
* ({@code SPLIT}).
*/
static MoveResponse checkMove(
GameState gs, String playerId, int cardId, PawnId pawnId, int steps) {
GameState gs, String playerId, int cardId, PawnId pawnId, int steps, MoveType moveType) {
MoveRequest req = new MoveRequest();
req.setPlayerId(playerId);
req.setCardId(cardId);
req.setPawn1Id(pawnId);
req.setStepsPawn1(steps);
req.setMoveType(MOVE);
req.setMoveType(moveType);
req.setTempMessageType(CHECK_MOVE);
MoveResponse resp = new MoveResponse();
ProcessOnMove.process(gs, req, resp);
Expand Down
26 changes: 25 additions & 1 deletion backend/src/main/java/adg/processing/MovePreconditions.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package adg.processing;

import static adg.util.CardValueCheck.isFour;
import static adg.util.CardValueCheck.isJack;
import static adg.util.CardValueCheck.isKing;
import static adg.util.CardValueCheck.isSeven;
import static com.adg.openapi.model.MoveResult.CANNOT_MAKE_MOVE;
import static com.adg.openapi.model.MoveResult.INVALID_SELECTION;
import static com.adg.openapi.model.MoveResult.PLAYER_DOES_NOT_HAVE_CARD;
import static com.adg.openapi.model.MoveType.SPLIT;

import adg.keezen.GameState;
import com.adg.openapi.model.Card;
Expand All @@ -17,13 +21,16 @@
/**
* What a move has to satisfy before there is any point working out its route: a real pawn and card
* were named, the pawn is on the board rather than in the nest, the player actually holds the card,
* and the pawns are theirs to move.
* asks for the card's own number of steps, and the pawns are theirs to move.
*
* <p>Separate from the routing because these are questions about the REQUEST, answerable without
* walking a single tile — and because a refusal here says nothing about the board's geometry.
*/
final class MovePreconditions {

/** The steps of a seven: a split's half may be anything from none to all of them. */
private static final int SEVEN_STEPS = 7;

private MovePreconditions() {}

/** Why a move was refused: the result to report, and the reason shown to the player. */
Expand All @@ -40,9 +47,26 @@ static Optional<Refusal> check(GameState gs, MoveRequest request, Pawn pawn1, Ca
if (!gs.playerHasCard(request.getPlayerId(), card)) {
return refuse(PLAYER_DOES_NOT_HAVE_CARD, MoveRejectionReason.DONT_HAVE_CARD);
}
if (!stepsFitTheCard(request, card)) {
return refuse(INVALID_SELECTION, MoveRejectionReason.INVALID_SELECTION);
}
return checkPawnOwnership(gs, request, card);
}

/**
* Whether the request asks for the card's own number of steps; the client's word is not taken
* for it. A normal move walks the card's value — a four backwards, an ace one step — and a King
* or Jack never makes one: those bring a pawn onto the board and switch two pawns. Half of a
* 7-split may be anything from 0 to 7 steps; the split itself checks that the halves add up to 7.
*/
private static boolean stepsFitTheCard(MoveRequest request, Card card) {
Integer steps = request.getStepsPawn1();
if (steps == null) return false;
if (request.getMoveType() == SPLIT) return isSeven(card) && steps >= 0 && steps <= SEVEN_STEPS;
if (isKing(card) || isJack(card)) return false;
return steps == (isFour(card) ? -4 : card.getValue());
}

/**
* A Jack switches with someone else's pawn, so it is the one card allowed to name a pawn that is
* not the player's. Otherwise both named pawns must be theirs to move — their own, or a
Expand Down
38 changes: 25 additions & 13 deletions backend/src/main/java/adg/processing/ProcessOnSplit.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ private void execute() {
// you play your teammate's pawns once all of your own are home. ProcessOnMove still checks,
// per pawn, that the mover is allowed to control it.
playerId = moveMessage.getPlayerId();
if (!bothStepsAreGiven()) return;
nrStepsPawn1 = moveMessage.getStepsPawn1();
nrStepsPawn2 = moveMessage.getStepsPawn2();

Expand All @@ -77,7 +78,7 @@ private void execute() {
if (!bothPawnMovesAreValid()) return;

if (gs.isMakeMove(moveMessage)) {
if (!executeSplitMoves()) return;
executeSplitMoves();
}

buildSplitResponse();
Expand All @@ -93,6 +94,14 @@ private boolean selectionIsValid() {
return true;
}

private boolean bothStepsAreGiven() {
if (moveMessage.getStepsPawn1() == null || moveMessage.getStepsPawn2() == null) {
reject(response, INVALID_SELECTION, MoveRejectionReason.INVALID_SELECTION);
return false;
}
return true;
}

private boolean pawnsAreSamePlayer() {
if (!pawn1.getPlayerId().equals(pawn2.getPlayerId())) {
reject(response, CANNOT_MAKE_MOVE, MoveRejectionReason.SPLIT_NEEDS_TWO_OWN_PAWNS);
Expand All @@ -114,6 +123,12 @@ private boolean stepsAddUpToSeven() {
reject(response, INVALID_SELECTION, MoveRejectionReason.SPLIT_STEPS_NOT_SEVEN);
return false;
}
// 0 + 7 is a split too — it lets the player switch between splitting and one pawn walking all 7
// — but a pawn never walks a negative half backwards.
if (nrStepsPawn1 < 0 || nrStepsPawn2 < 0) {
reject(response, INVALID_SELECTION, MoveRejectionReason.INVALID_SELECTION);
return false;
}
return true;
}

Expand All @@ -138,15 +153,17 @@ private MoveRequest buildCheckMoveRequest(PawnId pawnId, int nrSteps) {
// ── Move validation ───────────────────────────────────────────────────────

/**
* Pawn 1 is checked on the board as it is; pawn 2 on the board as it will be once pawn 1 has
* moved — a what-if board, so the check never moves a pawn, not even for a moment. (It used to
* move pawn 1 there and back, and checks running side by side could each catch the other
* half-done, and put pawn 1 "back" on a tile it had only borrowed.)
* Both halves have to be makeable; any other answer about either one — however it was refused —
* refuses the split, since there is no path to carry on from. Pawn 1 is checked on the board as
* it is; pawn 2 on the board as it will be once pawn 1 has moved — a what-if board, so the check
* never moves a pawn, not even for a moment. (It used to move pawn 1 there and back, and checks
* running side by side could each catch the other half-done, and put pawn 1 "back" on a tile it
* had only borrowed.)
*/
private boolean bothPawnMovesAreValid() {
moveResponsePawn1 = new MoveResponse();
ProcessOnMove.process(gs, moveMessagePawn1, moveResponsePawn1);
if (moveResponsePawn1.getResult().equals(CANNOT_MAKE_MOVE)) {
if (!CAN_MAKE_MOVE.equals(moveResponsePawn1.getResult())) {
// Surface the reason the first pawn's part of the split could not be made.
reject(response, moveResponsePawn1.getResult(),
moveResponsePawn1.getRejectionReason(), moveResponsePawn1.getRejectionDetail());
Expand All @@ -157,7 +174,7 @@ private boolean bothPawnMovesAreValid() {
gs.board().withPawnMovedTo(pawn1, moveResponsePawn1.getMovePawn1().getLast());
moveResponsePawn2 = new MoveResponse();
ProcessOnMove.check(gs, afterPawn1, moveMessagePawn2, moveResponsePawn2);
if (moveResponsePawn2.getResult().equals(CANNOT_MAKE_MOVE)) {
if (!CAN_MAKE_MOVE.equals(moveResponsePawn2.getResult())) {
// Surface the reason the second pawn's part of the split could not be made.
reject(response, moveResponsePawn2.getResult(),
moveResponsePawn2.getRejectionReason(), moveResponsePawn2.getRejectionDetail());
Expand All @@ -169,17 +186,12 @@ private boolean bothPawnMovesAreValid() {

// ── Move execution ────────────────────────────────────────────────────────

private boolean executeSplitMoves() {
if (moveMessage.getStepsPawn1() + moveMessage.getStepsPawn2() != 7) {
reject(response, INVALID_SELECTION, MoveRejectionReason.SPLIT_STEPS_NOT_SEVEN);
return false;
}
private void executeSplitMoves() {
gs.duplicatePlayerCard(playerId, card);
moveMessagePawn1.setTempMessageType(MAKE_MOVE);
moveMessagePawn2.setTempMessageType(MAKE_MOVE);
ProcessOnMove.process(gs, moveMessagePawn1, moveResponsePawn1, false);
ProcessOnMove.process(gs, moveMessagePawn2, moveResponsePawn2, true);
return true;
}

// ── Response assembly ─────────────────────────────────────────────────────
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ private static int forwardIndex(GameState gs, String ownerId, PositionKey tile)

private static MoveResponse checkSingleMove(
GameState gs, MoveRequest base, PawnId pawnId, int cardId, int steps) {
return MoveChecks.checkMove(gs, base.getPlayerId(), cardId, pawnId, steps);
return MoveChecks.checkMove(gs, base.getPlayerId(), cardId, pawnId, steps, SPLIT);
}

private static PositionKey lastTile(List<PositionKey> move) {
Expand Down
2 changes: 2 additions & 0 deletions backend/src/main/java/adg/services/MovesApiDelegateImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ private ResponseEntity<MoveResponse> dispatchMove(
response.setRejectionReason(MoveRejectionReason.MUST_FINISH_OWN_PAWNS_FIRST);
return new ResponseEntity<>(response, HttpStatus.OK);
}
// The server decides what kind of move this is, not the client: the steps are checked by kind.
moveRequest.setMoveType(validation.getMoveType());
switch (validation.getMoveType()) {
case MOVE -> ProcessOnMove.process(gameState, moveRequest, response);
case SPLIT -> ProcessOnSplit.process(gameState, moveRequest, response);
Expand Down
4 changes: 4 additions & 0 deletions backend/src/main/java/adg/util/CardValueCheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ public static boolean isAce(Card card) {
return card.getValue() == 1;
}

public static boolean isFour(Card card) {
return card.getValue() == 4;
}

public static boolean isSeven(Card card) {
return card.getValue() == 7;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package adg.keezen.ApiTests;

import static org.junit.jupiter.api.Assertions.assertEquals;

import adg.keezen.ApiUtils.ApiUtil;
import adg.keezen.utils.ApiCallsHelper;
import adg.keezen.utils.BaseUnitTest;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;

/**
* The server, not the client, decides what kind of move a request is: the steps are checked by
* that kind, so a request cannot pick the looser rule by naming another one.
*/
class StepsMatchCardApiTest extends BaseUnitTest {

private static final int SEVEN = 7;

private final ApiCallsHelper api = new ApiCallsHelper();

// Half of a split may be anything from 0 to 7 steps; a seven played whole must be 7. With one
// pawn the server routes this as a normal move, whatever the request calls it.
@Test
void aSevenWalkingThreeStepsWithOnePawn_IsRefused_EvenWhenTheRequestCallsItASplit() {
// GIVEN player 0 on turn, holding a seven, with a pawn on the board
String sessionId = ApiUtil.createStandardGame();
String player0 = ApiUtil.getPlayerid(sessionId, 0);
api.setHandForPlayer(sessionId, player0, SEVEN);
ApiUtil.setPawnPosition(sessionId, player0, 0, player0, 3);

// WHEN that one pawn walks 3 steps with it, in a request that says it is a split
Map<String, Object> response =
api.makeMove(
sessionId,
player0,
Map.of(
"playerId", player0,
"cardId", SEVEN, // a card's uuid is its value in setHandForPlayer
"pawn1Id", Map.of("playerId", player0, "pawnNr", 0),
"stepsPawn1", 3,
"moveType", "split",
"tempMessageType", "MAKE_MOVE"));

// THEN it is refused, the pawn has not budged, and the seven is still in hand
assertEquals("INVALID_SELECTION", response.get("result"));
assertEquals(3, tileOfPawn(sessionId, player0, 0));
assertEquals(List.of(SEVEN), cardValues(api.getPlayerCards(sessionId, player0)));
}

private static List<Object> cardValues(List<Map<String, Object>> cards) {
return cards.stream().map(card -> card.get("value")).toList();
}

/** The tile a pawn stands on, read from the game state as every client reads it. */
@SuppressWarnings("unchecked")
private int tileOfPawn(String sessionId, String playerId, int pawnNr) {
List<Map<String, Object>> pawns =
(List<Map<String, Object>>) api.getGameState(sessionId).get("pawns");
return pawns.stream()
.filter(pawn -> pawn.get("pawnId").equals(Map.of("playerId", playerId, "pawnNr", pawnNr)))
.map(pawn -> (Integer) ((Map<String, Object>) pawn.get("currentTileId")).get("tileNr"))
.findFirst()
.orElseThrow();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -463,11 +463,11 @@ void alreadyOnFinish_OvershootsCap_ForwardMove_CannotMove() {

@Test
void alreadyOnFinish_OvershootsCap_ExitsFinish_CannotMove() {
// pawn at (1,19) + 4 steps → bounces off cap and exits finish to (0,15)
// pawn at (1,18) + 5 steps → bounces off cap and exits finish to (0,15)
// → without setting: lands at (0,15)
// GIVEN
Card card = givePlayerCard(cardsDeck, 1, 4);
Pawn pawn1 = placePawnOnBoard(gameState, new PawnId("1", 0), new PositionKey("1", 19));
Card card = givePlayerCard(cardsDeck, 1, 5);
Pawn pawn1 = placePawnOnBoard(gameState, new PawnId("1", 0), new PositionKey("1", 18));

// WHEN
createMoveRequest(moveMessage, pawn1, card);
Expand All @@ -476,6 +476,6 @@ void alreadyOnFinish_OvershootsCap_ExitsFinish_CannotMove() {
// THEN
assertEquals(CANNOT_MAKE_MOVE, moveResponse.getResult());
assertNull(moveResponse.getPawn1());
assertEquals(new PositionKey("1", 19), gameState.getPawn(pawn1).getCurrentTileId());
assertEquals(new PositionKey("1", 18), gameState.getPawn(pawn1).getCurrentTileId());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,21 @@ void exactMoveRequired_forwardBlocked_noReversal_noMoveAvailable() {
assertFalse(MoveAvailabilityChecker.hasAvailableMove(gameState, "0", List.of(card)));
}

/**
* exactMoveRequired=true, and a four only: backwards it would land exactly on a blocked start
* tile and have to turn around, so it is refused — no move available → can forfeit. Four steps
* forwards would be free, so this also proves the four is tried backwards, as it is played.
*/
@Test
void exactMoveRequired_fourLandsOnBlockedStartTile_forwardWouldBeFree_noMoveAvailable() {
gameState.setExactMoveRequired(true);
Card card = givePlayerCard(cardsDeck, 0, 4);
placePawnOnNest(gameState, "0", new PositionKey("1", 4));
placePawnOnNest(gameState, "1", new PositionKey("1", 0)); // blockade

assertFalse(MoveAvailabilityChecker.hasAvailableMove(gameState, "0", List.of(card)));
}

/**
* exactMoveRequired=false, pawn inside the finish lane, ping-pong move available.
* Without exactMoveRequired a pawn closed in by own pawns can ping-pong → CAN_MAKE_MOVE.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,8 @@ void MoveOutOfFinishTileWhenAlreadyOnFinishTile_ByMovingBackwards() {
@Test
void MoveOutOfFinishTileWhenAlreadyOnFinishTile_ByMovingForwards() {
// GIVEN
Card card = givePlayerCard(cardsDeck, 1, 4);
Pawn pawn1 = placePawnOnNest(gameState, "1", new PositionKey("1", 19));
Card card = givePlayerCard(cardsDeck, 1, 5);
Pawn pawn1 = placePawnOnNest(gameState, "1", new PositionKey("1", 18));

// WHEN
createMoveRequest(moveMessage, pawn1, card);
Expand Down
Loading
Loading