Extract logic to check if move to column is legal

This commit is contained in:
ItsDrike 2024-12-03 01:54:01 +01:00
parent 408457e7ce
commit c47f973873
Signed by: ItsDrike
GPG key ID: FA2745890B7048C0
2 changed files with 22 additions and 23 deletions

View file

@ -85,29 +85,7 @@ bool GameState::moveCardToColumn(int columnId)
// We'll be moving the last card in the throwaway pile (maybe) // We'll be moving the last card in the throwaway pile (maybe)
PlayingCard *cardToMove = m_throwawayPile.last(); PlayingCard *cardToMove = m_throwawayPile.last();
if (m_columns[columnId].isEmpty()) { if (!isMoveToColumnLegal(cardToMove, columnId))
// If the column is empty, we can only place a king
if (cardToMove->value() != PlayingCard::Value::King)
return false;
ColumnSlot *col = new ColumnSlot(cardToMove, true);
m_columns[columnId].append(col);
m_throwawayPile.removeLast();
emit throwawayPileChanged();
emit columnsChanged();
return true;
}
// We'll be comparing this card against the last card in the column
PlayingCard* columnCard = m_columns[columnId].last()->card();
// This card's value must be one less than the card in the column
if (cardToMove->value() != columnCard->value() - 1)
return false;
// This card must be of opposite color
if (!PlayingCard::areOppositeColors(*cardToMove, *columnCard))
return false; return false;
ColumnSlot *col = new ColumnSlot(cardToMove, true); ColumnSlot *col = new ColumnSlot(cardToMove, true);
@ -221,6 +199,26 @@ bool GameState::tryMoveCardToFoundation(PlayingCard::Suit foundationId, PlayingC
return true; return true;
} }
bool GameState::isMoveToColumnLegal(PlayingCard *cardToMove, int columnId)
{
assert(columnId >= 0 && columnId < 7);
if (m_columns[columnId].isEmpty()) {
// Column is empty: only a King can be placed in an empty column
return cardToMove->value() == PlayingCard::Value::King;
}
// Compare against the last card in the column
PlayingCard* columnCard = m_columns[columnId].last()->card();
// The card's value must be one less than the card in the column
if (cardToMove->value() != columnCard->value() - 1)
return false;
// The card must be of opposite color
return PlayingCard::areOppositeColors(*cardToMove, *columnCard);
}
void GameState::ensureColumnRevealed(int columnId) void GameState::ensureColumnRevealed(int columnId)
{ {
assert(columnId >= 0 && columnId < 7); assert(columnId >= 0 && columnId < 7);

View file

@ -47,6 +47,7 @@ private:
bool m_gameWon; bool m_gameWon;
bool tryMoveCardToFoundation(PlayingCard::Suit foundationId, PlayingCard* cardToMove); bool tryMoveCardToFoundation(PlayingCard::Suit foundationId, PlayingCard* cardToMove);
bool isMoveToColumnLegal(PlayingCard* cardToMove, int columnId);
void ensureColumnRevealed(int columnId); void ensureColumnRevealed(int columnId);
}; };