diff --git a/gamestate.cpp b/gamestate.cpp index 6a3aa2b..e6a5847 100644 --- a/gamestate.cpp +++ b/gamestate.cpp @@ -85,29 +85,7 @@ bool GameState::moveCardToColumn(int columnId) // We'll be moving the last card in the throwaway pile (maybe) PlayingCard *cardToMove = m_throwawayPile.last(); - if (m_columns[columnId].isEmpty()) { - // 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)) + if (!isMoveToColumnLegal(cardToMove, columnId)) return false; ColumnSlot *col = new ColumnSlot(cardToMove, true); @@ -221,6 +199,26 @@ bool GameState::tryMoveCardToFoundation(PlayingCard::Suit foundationId, PlayingC 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) { assert(columnId >= 0 && columnId < 7); diff --git a/gamestate.h b/gamestate.h index 8ed45c8..54cd9f4 100644 --- a/gamestate.h +++ b/gamestate.h @@ -47,6 +47,7 @@ private: bool m_gameWon; bool tryMoveCardToFoundation(PlayingCard::Suit foundationId, PlayingCard* cardToMove); + bool isMoveToColumnLegal(PlayingCard* cardToMove, int columnId); void ensureColumnRevealed(int columnId); };