diff --git a/gamestate.cpp b/gamestate.cpp index 2817c4c..69bdedc 100644 --- a/gamestate.cpp +++ b/gamestate.cpp @@ -15,8 +15,8 @@ GameState::GameState(QObject *parent) void GameState::dealCards() { - // BUG: This causes a memory leak when called again qDebug() << "Dealing cards"; + cleanupBoard(false); QList deck = PlayingCard::createDeck(); @@ -45,14 +45,6 @@ void GameState::dealCards() assert(index == 28); m_drawPile = deck.mid(index); - // Reset the foundation & throwaway pile - m_throwawayPile.clear(); - for (auto &column : m_foundation) - column.clear(); - - // Note that we don't need to reset gameWon from here, as it's - // auto-checked from onFoundationChanged, which the emits trigger - emit drawPileChanged(); emit throwawayPileChanged(); emit columnsChanged(); @@ -63,6 +55,7 @@ void GameState::setupWinningDeck() { // BUG: This causes a memory leak when called again qDebug() << "Setting up a winning deck"; + cleanupBoard(false); // Create a sorted deck of cards (4 suits, ordered) QList deck = PlayingCard::createDeck(); @@ -379,6 +372,49 @@ void GameState::onFoundationChanged() emit gameWonChanged(); } +void GameState::cleanupBoard(bool emitChanges) +{ + // Clean up all PlayingCard objects in the draw pile + for (auto &card : m_drawPile) { + card->deleteLater(); + } + m_drawPile.clear(); + + // Clean up all PlayingCard objects in the throwaway pile + for (auto &card : m_throwawayPile) { + card->deleteLater(); + } + m_throwawayPile.clear(); + + // Clean up all PlayingCard objects in the foundation piles + for (auto &foundationPile : m_foundation) { + for (auto card : foundationPile) + card->deleteLater(); + foundationPile.clear(); + } + + // Clean up all ColumnSlot objects in the columns + // alongside with the associated PlayingCard objects + // that they hold + for (auto &column : m_columns) { + for (auto slot : column) { + slot->card()->deleteLater(); + slot->deleteLater(); + } + column.clear(); + } + + // Note that we don't need to reset gameWon from here, as it's + // auto-checked from onFoundationChanged, which the emits trigger + + if (emitChanges) { + emit drawPileChanged(); + emit throwawayPileChanged(); + emit foundationChanged(); + emit columnsChanged(); + } +} + bool GameState::tryAutoMoveSingleCard(PlayingCard &cardToMove, int skipColumnId) { // 1. Try moving the card to the foundation diff --git a/gamestate.h b/gamestate.h index c313290..1060050 100644 --- a/gamestate.h +++ b/gamestate.h @@ -59,6 +59,8 @@ private: QList> m_foundation; bool m_gameWon; + void cleanupBoard(bool emitChanges); + bool tryAutoMoveSingleCard(PlayingCard& cardToMove, int skipColumnId = -1); bool tryAutoMoveMultipleCards(const QList& cards, int skipColumnId);