Ejemplo n.º 1
0
    void operator()(const InnerDecklistNode *node, const DecklistCardNode *card) const
    {
        //Get the card name
        CardInfo * dbCard = db->getCard(card->getName());
        if (!dbCard || dbCard->getIsToken())
        {
            //If it's a token, we don't care about the card.
            return;
        }

        //Check if it's a sideboard card.
        if (node->getName() == DECK_ZONE_SIDE)
        {
            //Get the number of cards and add the card name
            sideBoardCards+=QString::number(card->getNumber());
            //Add a space between card num and name
            sideBoardCards+="%20";
            //Add card name
            sideBoardCards+=card->getName();
            //Add a return at the end of the card
            sideBoardCards+="%0A";
        }
        else //If it's a mainboard card, do the same thing, but for the mainboard card string
        {
            mainBoardCards+=QString::number(card->getNumber());
            mainBoardCards+="%20";
            mainBoardCards+=card->getName();
            mainBoardCards+="%0A";
        }
    }
Ejemplo n.º 2
0
void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle)
{
    qreal scaleFactor = translatedSize.width() / boundingRect().width();
    
    CardInfo *imageSource = facedown ? db->getCard() : info;
    QPixmap *translatedPixmap = imageSource->getPixmap(translatedSize.toSize());
    painter->save();
    QColor bgColor = Qt::transparent;
    if (translatedPixmap) {
        painter->save();
        transformPainter(painter, translatedSize, angle);
        painter->drawPixmap(QPointF(0, 0), *translatedPixmap);
        painter->restore();
    } else {
        QString colorStr;
        if (!color.isEmpty())
            colorStr = color;
        else if (info->getColors().size() > 1)
            colorStr = "m";
        else if (!info->getColors().isEmpty())
            colorStr = info->getColors().first().toLower();
        
        if (colorStr == "b")
            bgColor = QColor(0, 0, 0);
        else if (colorStr == "u")
            bgColor = QColor(0, 140, 180);
        else if (colorStr == "w")
            bgColor = QColor(255, 250, 140);
        else if (colorStr == "r")
            bgColor = QColor(230, 0, 0);
        else if (colorStr == "g")
            bgColor = QColor(0, 160, 0);
        else if (colorStr == "m")
            bgColor = QColor(250, 190, 30);
        else
            bgColor = QColor(230, 230, 230);
    }
    painter->setBrush(bgColor);
    QPen pen(Qt::black);
    pen.setWidth(2);
    painter->setPen(pen);
    painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 2));
    
    if (!translatedPixmap || settingsCache->getDisplayCardNames() || facedown) {
        painter->save();
        transformPainter(painter, translatedSize, angle);
        painter->setPen(Qt::white);
        painter->setBackground(Qt::black);
        painter->setBackgroundMode(Qt::OpaqueMode);
        QString nameStr;
        if (facedown)
            nameStr = "# " + QString::number(id);
        else
            nameStr = name;
        painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr);
        painter->restore();
    }
    
    painter->restore();
}
Ejemplo n.º 3
0
CardInfo *OracleImporter::addCard(const QString &setName,
                                  QString cardName,
                                  bool isToken,
                                  int cardId,
                                  QString &setNumber,
                                  QString &cardCost,
                                  QString &cmc,
                                  const QString &cardType,
                                  const QString &cardPT,
                                  int cardLoyalty,
                                  const QString &cardText,
                                  const QStringList & colors,
                                  const QStringList & relatedCards,
                                  const QStringList & reverseRelatedCards,
                                  bool upsideDown
                                  )
{
    QStringList cardTextRows = cardText.split("\n");

    // Workaround for card name weirdness
    cardName = cardName.replace("Æ", "AE");
    cardName = cardName.replace("’", "'");

    CardInfo * card;
    if (cards.contains(cardName)) {
        card = cards.value(cardName);
    } else {
        // Remove {} around mana costs
        cardCost.remove(QChar('{'));
        cardCost.remove(QChar('}'));

        // detect mana generator artifacts
        bool mArtifact = false;
        if (cardType.endsWith("Artifact"))
            for (int i = 0; i < cardTextRows.size(); ++i)
                if (cardTextRows[i].contains("{T}") && cardTextRows[i].contains("to your mana pool"))
                    mArtifact = true;

        // detect cards that enter the field tapped
        bool cipt = cardText.contains("Hideaway") || (cardText.contains(cardName + " enters the battlefield tapped") && !cardText.contains(cardName + " enters the battlefield tapped unless"));
        
        // insert the card and its properties
        card = new CardInfo(cardName, isToken, cardCost, cmc, cardType, cardPT, cardText, colors, relatedCards, reverseRelatedCards, upsideDown, cardLoyalty, cipt);
        int tableRow = 1;
        QString mainCardType = card->getMainCardType();
        if ((mainCardType == "Land") || mArtifact)
            tableRow = 0;
        else if ((mainCardType == "Sorcery") || (mainCardType == "Instant"))
            tableRow = 3;
        else if (mainCardType == "Creature")
            tableRow = 2;
        card->setTableRow(tableRow);
        
        cards.insert(cardName, card);
    }
    card->setMuId(setName, cardId);
    card->setSetNumber(setName, setNumber);

    return card;
}
Ejemplo n.º 4
0
bool CardDatabase::saveToFile(const QString &fileName, bool tokens)
{
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly))
        return false;
    QXmlStreamWriter xml(&file);

    xml.setAutoFormatting(true);
    xml.writeStartDocument();
    xml.writeStartElement("cockatrice_carddatabase");
    xml.writeAttribute("version", QString::number(versionNeeded));

    if (!tokens) {
        xml.writeStartElement("sets");
        QHashIterator<QString, CardSet *> setIterator(sets);
        while (setIterator.hasNext())
            xml << setIterator.next().value();
        xml.writeEndElement(); // sets
    }

    xml.writeStartElement("cards");
    QHashIterator<QString, CardInfo *> cardIterator(cards);
    while (cardIterator.hasNext()) {
        CardInfo *card = cardIterator.next().value();
        if (tokens == card->getIsToken()) {
            xml << card;
        }
    }
    xml.writeEndElement(); // cards

    xml.writeEndElement(); // cockatrice_carddatabase
    xml.writeEndDocument();

    return true;
}
Ejemplo n.º 5
0
QModelIndex DeckListModel::addCard(const QString &cardName, const QString &zoneName)
{
	InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root);

	CardInfo *info = db->getCard(cardName);
	QString cardType = info->getMainCardType();
	InnerDecklistNode *cardTypeNode = createNodeIfNeeded(cardType, zoneNode);

	DecklistModelCardNode *cardNode = dynamic_cast<DecklistModelCardNode *>(cardTypeNode->findChild(cardName));
	if (!cardNode) {
		DecklistCardNode *decklistCard = deckList->addCard(cardName, zoneName);
		QModelIndex parentIndex = nodeToIndex(cardTypeNode);
		beginInsertRows(parentIndex, cardTypeNode->size(), cardTypeNode->size());
		cardNode = new DecklistModelCardNode(decklistCard, cardTypeNode);
		endInsertRows();
		sort(1);
		emitRecursiveUpdates(parentIndex);
		return nodeToIndex(cardNode);
	} else {
		cardNode->setNumber(cardNode->getNumber() + 1);
		QModelIndex ind = nodeToIndex(cardNode);
		emitRecursiveUpdates(ind);
		return ind;
	}
}
Ejemplo n.º 6
0
void DeckListModel::rebuildTree()
{
    beginResetModel();

    root->clearTree();
    InnerDecklistNode *listRoot = deckList->getRoot();
    for (int i = 0; i < listRoot->size(); i++) {
        InnerDecklistNode *currentZone = dynamic_cast<InnerDecklistNode *>(listRoot->at(i));
        InnerDecklistNode *node = new InnerDecklistNode(currentZone->getName(), root);
        for (int j = 0; j < currentZone->size(); j++) {
            DecklistCardNode *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
            // XXX better sanity checking
            if (!currentCard)
                continue;

            CardInfo *info = db->getCard(currentCard->getName());
            QString cardType;
            if (!info)
                cardType = "unknown";
            else
                cardType = info->getMainCardType();
            InnerDecklistNode *cardTypeNode = dynamic_cast<InnerDecklistNode *>(node->findChild(cardType));
            if (!cardTypeNode)
                cardTypeNode = new InnerDecklistNode(cardType, node);

            new DecklistModelCardNode(currentCard, cardTypeNode);
        }
    }

    endResetModel();
}
Ejemplo n.º 7
0
CardInfo *CardDatabase::getCardFromMap(CardNameMap &cardMap, const QString &cardName, bool createIfNotFound) {
    if (cardName.isEmpty())
        return noCard;
    else if (cardMap.contains(cardName))
        return cardMap.value(cardName);
    else if (createIfNotFound) {
        CardInfo *newCard = new CardInfo(this, cardName, true);
        newCard->addToSet(getSet(CardDatabase::TOKENS_SETNAME));
        cardMap.insert(cardName, newCard);
        return newCard;
    } else
        return 0;
}
Ejemplo n.º 8
0
CardInfo *CardDatabase::getCardFromMap(CardNameMap &cardMap, const QString &cardName, bool createIfNotFound) {
    CardInfo *foundCard;

    if (cardName.isEmpty())
        return noCard;
    else if (cardMap.contains(cardName))
        return cardMap.value(cardName);
    else if ((foundCard = cardMap.findByPrefix(cardName.toStdString())))
        return foundCard;
    else if (createIfNotFound) {
        CardInfo *newCard = new CardInfo(this, cardName, true);
        newCard->addToSet(getSet("TK"));
        cardMap.insert(cardName, newCard);
        return newCard;
    } else
        return 0;
}
Ejemplo n.º 9
0
void PictureLoader::cacheCardPixmaps(QList<CardInfo *> cards)
{
    QPixmap tmp;
    int max = qMin(cards.size(), CACHED_CARD_PER_DECK_MAX);
    for (int i = 0; i < max; ++i)
    {
        CardInfo * card = cards.at(i);
        if(!card)
            continue;

        QString key = card->getPixmapCacheKey();
        if(QPixmapCache::find(key, &tmp))
            continue;

        getInstance().enqueueImageLoad(card);
    }
}
Ejemplo n.º 10
0
/**
 * Update the prices of the cards in deckList.
 */
void DBPriceUpdater::updatePrices()
{
    QString base = "https://api.deckbrew.com/mtg/cards", q = "";
    QStringList cards = deck->getCardList();
    muidMap.clear();
    urls.clear();
    CardInfo * card;
    int muid;
    SetList sets;
    bool bNotFirst=false;

    for (int i = 0; i < cards.size(); ++i) {
        card = db->getCard(cards[i], false);
        sets = card->getSets();
        for(int j = 0; j < sets.size(); ++j)
        {
            muid=card->getMuId(sets[j]->getShortName());

            if (!muid) {
                continue;
            }

            //qDebug() << "muid " << muid << " card: " << cards[i] << endl;
            if(bNotFirst)
            {
                q += QString("&m=%1").arg(muid);
            } else {
                q += QString("?m=%1").arg(muid);
                bNotFirst = true;
            }
            muidMap.insert(muid, cards[i]);

            if(q.length() > 240)
            {
                urls.append(base + q);
                bNotFirst=false;
                q = "";
            }
        }
    }
    if(q.length() > 0)
        urls.append(base + q);

    requestNext();
}
Ejemplo n.º 11
0
void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if (!startItem)
        return;

    if (targetItem && (targetItem != startItem)) {
        CardZone *startZone = static_cast<CardItem *>(startItem)->getZone();
        // For now, we can safely assume that the start item is always a card.
        // The target item can be a player as well.
        CardItem *startCard = qgraphicsitem_cast<CardItem *>(startItem);
        CardItem *targetCard = qgraphicsitem_cast<CardItem *>(targetItem);

        Command_CreateArrow cmd;
        cmd.mutable_arrow_color()->CopyFrom(convertQColorToColor(color));
        cmd.set_start_player_id(startZone->getPlayer()->getId());
        cmd.set_start_zone(startZone->getName().toStdString());
        cmd.set_start_card_id(startCard->getId());

        if (targetCard) {
            CardZone *targetZone = targetCard->getZone();
            cmd.set_target_player_id(targetZone->getPlayer()->getId());
            cmd.set_target_zone(targetZone->getName().toStdString());
            cmd.set_target_card_id(targetCard->getId());
        } else {
            PlayerTarget *targetPlayer = qgraphicsitem_cast<PlayerTarget *>(targetItem);
            cmd.set_target_player_id(targetPlayer->getOwner()->getId());
        }
        if (startZone->getName().compare("hand") == 0)  {
            startCard->playCard(false);
            CardInfo *ci = startCard->getInfo();
            if (((!settingsCache->getPlayToStack() && ci->getTableRow() == 3) ||
                ((settingsCache->getPlayToStack() && ci->getTableRow() != 0) &&
                startCard->getZone()->getName().toStdString() != "stack")))
                cmd.set_start_zone("stack");
            else
                cmd.set_start_zone(settingsCache->getPlayToStack() ? "stack" :"table");
        }
        player->sendGameCommand(cmd);
    }
    delArrow();

    for (int i = 0; i < childArrows.size(); ++i)
        childArrows[i]->mouseReleaseEvent(event);
}
Ejemplo n.º 12
0
void DlgEditTokens::actAddToken()
{
    QString name;
    bool askAgain;
    do {
        name = QInputDialog::getText(this, tr("Add token"), tr("Please enter the name of the token:"));
        if (!name.isEmpty() && cardDatabaseModel->getDatabase()->getCard(name, false)) {
            QMessageBox::critical(this, tr("Error"), tr("The chosen name conflicts with an existing card or token."));
            askAgain = true;
        } else
            askAgain = false;
    } while (askAgain);
    
    if (name.isEmpty())
        return;
    
    CardInfo *card = new CardInfo(cardDatabaseModel->getDatabase(), name, true);
    card->addToSet(cardDatabaseModel->getDatabase()->getSet("TK"));
    card->setCardType("Token");
    cardDatabaseModel->getDatabase()->addCard(card);
}
Ejemplo n.º 13
0
DecklistModelCardNode *DeckListModel::findCardNode(const QString &cardName, const QString &zoneName) const
{
    InnerDecklistNode *zoneNode, *typeNode;
    CardInfo *info;
    QString cardType;

    zoneNode = dynamic_cast<InnerDecklistNode *>(root->findChild(zoneName));
    if(!zoneNode)
        return NULL;

    info = db->getCard(cardName);
    if(!info)
        return NULL;

    cardType = info->getMainCardType();
    typeNode = dynamic_cast<InnerDecklistNode *>(zoneNode->findChild(cardType));
    if(!typeNode)
        return NULL;

    return dynamic_cast<DecklistModelCardNode *>(typeNode->findChild(cardName));
}
Ejemplo n.º 14
0
bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const
{
	CardInfo *info = static_cast<CardDatabaseModel *>(sourceModel())->getCard(sourceRow);
	
	if (!cardNameBeginning.isEmpty())
		if (!info->getName().startsWith(cardNameBeginning, Qt::CaseInsensitive))
			return false;
	
	if (!cardName.isEmpty())
		if (!info->getName().contains(cardName, Qt::CaseInsensitive))
			return false;
	
	if (!cardText.isEmpty())
		if (!info->getText().contains(cardText, Qt::CaseInsensitive))
			return false;
	
	if (!cardColors.isEmpty())
		if (QSet<QString>::fromList(info->getColors()).intersect(cardColors).isEmpty() && !(info->getColors().isEmpty() && cardColors.contains("X")))
			return false;
		
	if (!cardTypes.isEmpty())
		if (!cardTypes.contains(info->getMainCardType()))
			return false;

	return true;
}
Ejemplo n.º 15
0
QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const
{
	if (!index.isValid())
		return QVariant();
	if ((index.row() >= cardList.size()) || (index.column() >= 5))
		return QVariant();
	if (role != Qt::DisplayRole)
		return QVariant();

	CardInfo *card = cardList.at(index.row());
	switch (index.column()){
		case 0: return card->getName();
		case 1: {
			QStringList setList;
			const QList<CardSet *> &sets = card->getSets();
			for (int i = 0; i < sets.size(); i++)
				setList << sets[i]->getShortName();
			return setList.join(", ");
		}
		case 2: return card->getManaCost();
		case 3: return card->getCardType();
		case 4: return card->getPowTough();
		default: return QVariant();
	}
}
Ejemplo n.º 16
0
void DlgEditTokens::tokenSelectionChanged(const QModelIndex &current, const QModelIndex & /* previous */)
{
    const QModelIndex realIndex = cardDatabaseDisplayModel->mapToSource(current);
    CardInfo *cardInfo = current.row() >= 0 ? cardDatabaseModel->getCard(realIndex.row()) : cardDatabaseModel->getDatabase()->getCard();
    if (!cardInfo->getName().isEmpty())
        currentCard = cardInfo;
    else
        currentCard = 0;
    
    nameEdit->setText(cardInfo->getName());
    const QString cardColor = cardInfo->getColors().isEmpty() ? QString() : (cardInfo->getColors().size() > 1 ? QString("m") : cardInfo->getColors().first());
    colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
    ptEdit->setText(cardInfo->getPowTough());
    annotationEdit->setText(cardInfo->getText());
}
Ejemplo n.º 17
0
QString PictureLoader::getPicUrl()
{
    if (!picDownload) return QString("");

    CardInfo *card = cardBeingDownloaded.getCard();
    CardSet *set=cardBeingDownloaded.getCurrentSet();
    QString picUrl = QString("");

    // if sets have been defined for the card, they can contain custom picUrls
    if(set)
    {
        // first check if Hq is enabled and a custom Hq card url exists in cards.xml
        if(picDownloadHq)
        {
            picUrl = card->getCustomPicURLHq(set->getShortName());
            if (!picUrl.isEmpty())
                return picUrl;
        }

        // then, test for a custom, non-Hq card url in cards.xml
        picUrl = card->getCustomPicURL(set->getShortName());
        if (!picUrl.isEmpty())
            return picUrl;
    }

    // if a card has a muid, use the default url; if not, use the fallback
    int muid = set ? card->getMuId(set->getShortName()) : 0;
    if(muid)
        picUrl = picDownloadHq ? settingsCache->getPicUrlHq() : settingsCache->getPicUrl();
    else
        picUrl = picDownloadHq ? settingsCache->getPicUrlHqFallback() : settingsCache->getPicUrlFallback();

    picUrl.replace("!name!", QUrl::toPercentEncoding(card->getCorrectedName()));
    picUrl.replace("!cardid!", QUrl::toPercentEncoding(QString::number(muid)));
    if (set) {
        picUrl.replace("!setcode!", QUrl::toPercentEncoding(set->getShortName()));
        picUrl.replace("!setname!", QUrl::toPercentEncoding(set->getLongName()));
    }

    if (picUrl.contains("!name!") ||
            picUrl.contains("!setcode!") ||
            picUrl.contains("!setname!") ||
            picUrl.contains("!cardid!")) {
        qDebug() << "Insufficient card data to download" << card->getName() << "Url:" << picUrl;
        return QString("");
    }

    return picUrl;
}
Ejemplo n.º 18
0
QString PictureLoader::getPicUrl()
{
    if (!picDownload) return QString("");

    CardInfo *card = cardBeingDownloaded.getCard();
    CardSet *set=cardBeingDownloaded.getCurrentSet();
    QString picUrl = QString("");

    // if sets have been defined for the card, they can contain custom picUrls
    if(set)
    {
        picUrl = card->getCustomPicURL(set->getShortName());
        if (!picUrl.isEmpty())
            return picUrl;
    }

    // if a card has a muid, use the default url; if not, use the fallback
    int muid = set ? card->getMuId(set->getShortName()) : 0;
    picUrl = muid ? settingsCache->getPicUrl() : settingsCache->getPicUrlFallback();

    picUrl.replace("!name!", QUrl::toPercentEncoding(card->getCorrectedName()));
    picUrl.replace("!name_lower!", QUrl::toPercentEncoding(card->getCorrectedName().toLower()));
    picUrl.replace("!cardid!", QUrl::toPercentEncoding(QString::number(muid)));
    if (set)
    {
        picUrl.replace("!setcode!", QUrl::toPercentEncoding(set->getShortName()));
        picUrl.replace("!setcode_lower!", QUrl::toPercentEncoding(set->getShortName().toLower()));
        picUrl.replace("!setname!", QUrl::toPercentEncoding(set->getLongName()));
        picUrl.replace("!setname_lower!", QUrl::toPercentEncoding(set->getLongName().toLower()));
    }

    if (
        picUrl.contains("!name!") ||
        picUrl.contains("!name_lower!") ||
        picUrl.contains("!setcode!") ||
        picUrl.contains("!setcode_lower!") ||
        picUrl.contains("!setname!") ||
        picUrl.contains("!setname_lower!") ||
        picUrl.contains("!cardid!")
        )
    {
        qDebug() << "Insufficient card data to download" << card->getName() << "Url:" << picUrl;
        return QString("");
    }

    return picUrl;
}
Ejemplo n.º 19
0
int OracleImporter::importTextSpoiler(CardSet *set, const QVariant &data)
{
    int cards = 0;

    QListIterator<QVariant> it(data.toList());
    QVariantMap map;
    QString cardName;
    QString cardCost;
    QString cardType;
    QString cardPT;
    QString cardText;
    int cardId;
    int cardLoyalty;
    QMap<int, QVariantMap> splitCards;

    while (it.hasNext()) {
        map = it.next().toMap();
        if(0 == QString::compare(map.value("layout").toString(), QString("split"), Qt::CaseInsensitive))
        {
            // Split card handling
            cardId = map.contains("multiverseid") ? map.value("multiverseid").toInt() : 0;
            if(splitCards.contains(cardId))
            {
                // merge two split cards
                QVariantMap tmpMap = splitCards.take(cardId);
                QVariantMap * card1 = 0, * card2 = 0;
                // same cardid
                cardId = map.contains("multiverseid") ? map.value("multiverseid").toInt() : 0;
                // this is currently an integer; can't accept 2 values
                cardLoyalty = 0;

                // determine which subcard is the first one in the split
                QStringList names=map.contains("names") ? map.value("names").toStringList() : QStringList("");
                if(names.count()>0 &&
                        map.contains("name") &&
                        0 == QString::compare(map.value("name").toString(), names.at(0)))
                {
                    // map is the left part of the split card, tmpMap is right part
                    card1 = &map;
                    card2 = &tmpMap;
                } else {
                    //tmpMap is the left part of the split card, map is right part
                    card1 = &tmpMap;
                    card2 = &map;
                }

                // add first card's data
                cardName = card1->contains("name") ? card1->value("name").toString() : QString("");
                cardCost = card1->contains("manaCost") ? card1->value("manaCost").toString() : QString("");
                cardType = card1->contains("type") ? card1->value("type").toString() : QString("");
                cardPT = card1->contains("power") || card1->contains("toughness") ? card1->value("power").toString() + QString('/') + card1->value("toughness").toString() : QString("");
                cardText = card1->contains("text") ? card1->value("text").toString() : QString("");

                // add second card's data
                cardName += card2->contains("name") ? QString(" // ") + card2->value("name").toString() : QString("");
                cardCost += card2->contains("manaCost") ? QString(" // ") + card2->value("manaCost").toString() : QString("");
                cardType += card2->contains("type") ? QString(" // ") + card2->value("type").toString() : QString("");
                cardPT += card2->contains("power") || card2->contains("toughness") ? QString(" // ") + card2->value("power").toString() + QString('/') + card2->value("toughness").toString() : QString("");
                cardText += card2->contains("text") ? QString("\n\n---\n\n") + card2->value("text").toString() : QString("");
            } else {
                // first card od a pair; enqueue for later merging
                splitCards.insert(cardId, map);
                continue;
            }
        } else {
            // normal cards handling
            cardName = map.contains("name") ? map.value("name").toString() : QString("");
            cardCost = map.contains("manaCost") ? map.value("manaCost").toString() : QString("");
            cardType = map.contains("type") ? map.value("type").toString() : QString("");
            cardPT = map.contains("power") || map.contains("toughness") ? map.value("power").toString() + QString('/') + map.value("toughness").toString() : QString("");
            cardText = map.contains("text") ? map.value("text").toString() : QString("");
            cardId = map.contains("multiverseid") ? map.value("multiverseid").toInt() : 0;
            cardLoyalty = map.contains("loyalty") ? map.value("loyalty").toInt() : 0;
        }

        CardInfo *card = addCard(set->getShortName(), cardName, false, cardId, cardCost, cardType, cardPT, cardLoyalty, cardText.split("\n"));

        if (!set->contains(card)) {
            card->addToSet(set);
            cards++;
        }
    }

    return cards;
}
Ejemplo n.º 20
0
int OracleImporter::importTextSpoiler(CardSet *set, const QByteArray &data)
{
	int cards = 0;
	QString bufferContents(data);
	
	// Workaround for ampersand bug in text spoilers
	int index = -1;
	while ((index = bufferContents.indexOf('&', index + 1)) != -1) {
		int semicolonIndex = bufferContents.indexOf(';', index);
		if (semicolonIndex > 5) {
			bufferContents.insert(index + 1, "amp;");
			index += 4;
		}
	}
	
	QDomDocument doc;
	QString errorMsg;
	int errorLine, errorColumn;
	if (!doc.setContent(bufferContents, &errorMsg, &errorLine, &errorColumn))
		qDebug() << "error:" << errorMsg << "line:" << errorLine << "column:" << errorColumn;

	QDomNodeList divs = doc.elementsByTagName("div");
	for (int i = 0; i < divs.size(); ++i) {
		QDomElement div = divs.at(i).toElement();
		QDomNode divClass = div.attributes().namedItem("class");
		if (divClass.nodeValue() == "textspoiler") {
			QString cardName, cardCost, cardType, cardPT, cardText;
			int cardId = 0;
			int cardLoyalty = 0;
			
			QDomNodeList trs = div.elementsByTagName("tr");
			for (int j = 0; j < trs.size(); ++j) {
				QDomElement tr = trs.at(j).toElement();
				QDomNodeList tds = tr.elementsByTagName("td");
				if (tds.size() != 2) {
					QStringList cardTextSplit = cardText.split("\n");
					for (int i = 0; i < cardTextSplit.size(); ++i)
						cardTextSplit[i] = cardTextSplit[i].trimmed();
					
					CardInfo *card = addCard(set->getShortName(), cardName, false, cardId, cardCost, cardType, cardPT, cardLoyalty, cardTextSplit);
					if (!set->contains(card)) {
						card->addToSet(set);
						cards++;
					}
					cardName = cardCost = cardType = cardPT = cardText = QString();
				} else {
					QString v1 = tds.at(0).toElement().text().simplified();
					QString v2 = tds.at(1).toElement().text().replace(trUtf8("—"), "-");
					
					if (v1 == "Name") {
						QDomElement a = tds.at(1).toElement().elementsByTagName("a").at(0).toElement();
						QString href = a.attributes().namedItem("href").nodeValue();
						cardId = href.mid(href.indexOf("multiverseid=") + 13).toInt();
						cardName = v2.simplified();
					} else if (v1 == "Cost:")
						cardCost = v2.simplified();
					else if (v1 == "Type:")
						cardType = v2.simplified();
					else if (v1 == "Pow/Tgh:")
						cardPT = v2.simplified().remove('(').remove(')');
					else if (v1 == "Rules Text:")
						cardText = v2.trimmed();
					else if (v1 == "Loyalty:")
						cardLoyalty = v2.trimmed().remove('(').remove(')').toInt();
				}
			}
			break;
		}
	}
	return cards;
}
Ejemplo n.º 21
0
CardInfo *OracleImporter::addCard(const QString &setName,
								  QString cardName,
								  bool isToken,
								  int cardId,
								  const QString &cardCost,
								  const QString &cardType,
								  const QString &cardPT,
								  int cardLoyalty,
								  const QStringList &cardText)
{
	QString fullCardText = cardText.join("\n");
	bool splitCard = false;
	if (cardName.contains('(')) {
		cardName.remove(QRegExp(" \\(.*\\)"));
		splitCard = true;
	}
	// Workaround for card name weirdness
	if (cardName.contains("XX"))
		cardName.remove("XX");
	cardName = cardName.replace("Æ", "AE");
        cardName = cardName.replace("’", "'");

	CardInfo *card;
	if (cardHash.contains(cardName)) {
		card = cardHash.value(cardName);
		if (splitCard && !card->getText().contains(fullCardText))
			card->setText(card->getText() + "\n---\n" + fullCardText);
	} else {
		bool mArtifact = false;
		if (cardType.endsWith("Artifact"))
			for (int i = 0; i < cardText.size(); ++i)
				if (cardText[i].contains("{T}") && cardText[i].contains("to your mana pool"))
					mArtifact = true;
					
		QStringList colors;
		QStringList allColors = QStringList() << "W" << "U" << "B" << "R" << "G";
		for (int i = 0; i < allColors.size(); i++)
			if (cardCost.contains(allColors[i]))
				colors << allColors[i];
		
		if (cardText.contains(cardName + " is white."))
			colors << "W";
		if (cardText.contains(cardName + " is blue."))
			colors << "U";
		if (cardText.contains(cardName + " is black."))
			colors << "B";
		if (cardText.contains(cardName + " is red."))
			colors << "R";
		if (cardText.contains(cardName + " is green."))
			colors << "G";
		
		bool cipt = (cardText.contains(cardName + " enters the battlefield tapped."));
		
		card = new CardInfo(this, cardName, isToken, cardCost, cardType, cardPT, fullCardText, colors, cardLoyalty, cipt);
		int tableRow = 1;
		QString mainCardType = card->getMainCardType();
		if ((mainCardType == "Land") || mArtifact)
			tableRow = 0;
		else if ((mainCardType == "Sorcery") || (mainCardType == "Instant"))
			tableRow = 3;
		else if (mainCardType == "Creature")
			tableRow = 2;
		card->setTableRow(tableRow);
		
		cardHash.insert(cardName, card);
	}
	card->setPicURL(setName, getPictureUrl(pictureUrl, cardId, cardName, setName));
	card->setPicURLHq(setName, getPictureUrl(pictureUrlHq, cardId, cardName, setName));
	card->setPicURLSt(setName, getPictureUrl(pictureUrlSt, cardId, cardName, setName));
	return card;
}
Ejemplo n.º 22
0
void InformationStorage::loadAll(string file)
{
	//Clear out the object types first
	terrainTypes.clear();
	buildingTypes.clear();
	unitTypes.clear();
	
	TiXmlDocument doc( file.c_str());
	if(doc.LoadFile())
	{
		TiXmlHandle hDoc(&doc);
		TiXmlElement* pElem;
		TiXmlHandle hRoot(0);
		pElem = hDoc.FirstChildElement().Element();
		hRoot=TiXmlHandle(pElem);


		//--------------------------------Load in Units----------------------

		TiXmlNode* pUnitNode=hRoot.FirstChild( "Units" ).FirstChild().ToNode();
		TiXmlNode* pUnitInfoNode;
		//For loop will cycle through each unit within the Units tag
		for( pUnitNode; pUnitNode; pUnitNode=pUnitNode->NextSiblingElement())
		{
			//Need to iterate through the data of a unit; can make a pointer to the first child of pUnitNode for ID, get NextSiblingElement for other elements, use 
			//query attributes for combat stats.
			UnitInfo u = UnitInfo();
			u.load(pUnitNode);
			unitTypes[u.id] = u;
		}



		//----------------------Load in Terrain-------------------------------

		TiXmlNode* pTerrainNode=hRoot.FirstChild( "Terrain" ).FirstChild().ToNode();
		TiXmlNode* pTerrainInfoNode;
		//For loop will cycle through each unit within the Units tag
		for( pTerrainNode; pTerrainNode; pTerrainNode=pTerrainNode->NextSiblingElement())
		{
			//Need to iterate through the data of a unit; can make a pointer to the first child of pUnitNode for ID, get NextSiblingElement for other elements, use 
			//query attributes for combat stats.
			TerrainInfo t = TerrainInfo();
			t.load(pTerrainNode);
			terrainTypes[t.id] = t;
		}


		//---------------------------------Load in Buildings--------------------------------------

		TiXmlNode* pBuildingNode=hRoot.FirstChild( "Buildings" ).FirstChild().ToNode();
		//TiXmlNode* pBuildingInfoNode;
		//TiXmlNode* pProductionIDNode;
		//For loop will cycle through each unit within the Units tag
		for( pBuildingNode; pBuildingNode; pBuildingNode=pBuildingNode->NextSiblingElement())
		{
			//Need to iterate through the data of a unit; can make a pointer to the first child of pUnitNode for ID, get NextSiblingElement for other elements, use 
			//query attributes for combat stats.
			BuildingInfo b = BuildingInfo();
			b.load(pBuildingNode);
			buildingTypes[b.id] = b;
		}

		//-------------------------------Load in Commander Cards--------------------------------
		TiXmlNode* pCardNode = hRoot.FirstChild( "Cards" ).FirstChild().ToNode();
		for( pCardNode; pCardNode; pCardNode=pCardNode->NextSiblingElement())
		{
			CardInfo c = CardInfo();
			c.load(pCardNode);
			cardTypes[c.id] = c;
		}


	}
	else
	{
		//std::cout << "\nFailed to load the units\n";
	}

	DeveloperConsole::write("Buildings Loaded: ");
	DeveloperConsole::writeLine(buildingTypes.size());
	DeveloperConsole::write("Units Loaded: ");
	DeveloperConsole::writeLine(unitTypes.size());
	DeveloperConsole::write("Terrain Loaded: ");
	DeveloperConsole::writeLine(terrainTypes.size());
	

}