solitare/playingcard.cpp

89 lines
2.3 KiB
C++
Raw Normal View History

2024-12-01 18:43:49 +00:00
#include "playingcard.h"
PlayingCard::PlayingCard(const PlayingCard::Suit &suit, const PlayingCard::Value &value, QObject *parent)
: QObject{parent}, m_suit{suit}, m_value{value}
2024-12-01 18:43:49 +00:00
{ }
PlayingCard::Suit PlayingCard::suit() const
2024-12-01 18:43:49 +00:00
{
return m_suit;
2024-12-01 18:43:49 +00:00
}
QString PlayingCard::suitString() const
2024-12-01 18:43:49 +00:00
{
switch (m_suit) {
case Clubs: return "clubs";
case Diamonds: return "diamonds";
case Hearts: return "hearts";
case Spades: return "spades";
default: throw std::invalid_argument("Invalid Suit enum value");
}
}
void PlayingCard::setSuit(const PlayingCard::Suit &suit)
{
if (m_suit == suit)
2024-12-01 18:43:49 +00:00
return;
m_suit = suit;
2024-12-02 23:33:22 +00:00
emit suitChanged();
2024-12-01 18:43:49 +00:00
}
PlayingCard::Value PlayingCard::value() const
2024-12-01 18:43:49 +00:00
{
return m_value;
}
QString PlayingCard::valueString() const
{
switch (m_value) {
case Ace: return "ace";
case Two: return "2";
case Three: return "3";
case Four: return "4";
case Five: return "5";
case Six: return "6";
case Seven: return "7";
case Eight: return "8";
case Nine: return "9";
case Ten: return "10";
case Jack: return "jack";
case Queen: return "queen";
case King: return "king";
default: throw std::invalid_argument("Invalid Value enum value");
}
}
void PlayingCard::setValue(const PlayingCard::Value &value)
2024-12-01 18:43:49 +00:00
{
if (m_value == value)
return;
m_value = value;
2024-12-02 23:33:22 +00:00
emit valueChanged();
2024-12-01 18:43:49 +00:00
}
QList<PlayingCard *> PlayingCard::createDeck()
{
QList<PlayingCard*> deck;
for (int suitIndex = PlayingCard::Suit::Clubs; suitIndex <= PlayingCard::Suit::Spades; ++suitIndex) {
for (int valueIndex = PlayingCard::Value::Ace; valueIndex <= PlayingCard::Value::King; ++valueIndex) {
PlayingCard *card = new PlayingCard();
card->setSuit(static_cast<PlayingCard::Suit>(suitIndex));
card->setValue(static_cast<PlayingCard::Value>(valueIndex));
deck.append(card);
}
}
return deck;
}
2024-12-01 21:40:42 +00:00
bool PlayingCard::areOppositeColors(const PlayingCard &card1, const PlayingCard &card2)
{
bool card1IsRed = (card1.suit() == Suit::Hearts || card1.suit() == Suit::Diamonds);
bool card2IsRed = (card2.suit() == Suit::Hearts || card2.suit() == Suit::Diamonds);
return card1IsRed != card2IsRed;
}