Example #1
0
 void handle(const ResultRecord &r) override
 {
     const Value& stack = r["stack"];
     int first = stack[0]["level"].toInt();
     QList<KDevelop::FrameStackModel::FrameItem> frames;
     for (int i = 0; i< stack.size(); ++i) {
         const Value& frame = stack[i];
         KDevelop::FrameStackModel::FrameItem f;
         f.nr = frame["level"].toInt();
         f.name = getFunctionOrAddress(frame);
         QPair<QString, int> loc = getSource(frame);
         f.file = QUrl::fromLocalFile(loc.first);
         f.line = loc.second;
         frames << f;
     }
     bool hasMore = false;
     if (!frames.isEmpty()) {
         if (frames.last().nr == m_to+1) {
             frames.takeLast();
             hasMore = true;
         }
     }
     if (first == 0) {
         model->setFrames(m_thread, frames);
     } else {
         model->insertFrames(m_thread, frames);
     }
     model->setHasMoreFrames(m_thread, hasMore);
 }
Example #2
0
void KRunnerModel::matchesChanged(const QList< Plasma::QueryMatch > & m)
{
    QList< Plasma::QueryMatch > matches = m;

    qSort(matches.begin(), matches.end());

    clear();

    while (matches.size()) {
        Plasma::QueryMatch match = matches.takeLast();

        appendRow(
            StandardItemFactory::createItem(
                match.icon(),
                match.text(),
                match.subtext(),
                QString("krunner://") + match.runner()->id() + "/" + ::runnerManager()->query() + "#" + match.id(),
                match.relevance(),
                CommonModel::AddAction
                )
            );
    }

    sort(0, Qt::DescendingOrder);
}
void BarDescriptorEditorAssetsWidget::removeAsset(const QString &fullPath)
{
    QList<QStandardItem*> assetItems = m_assetsModel->findItems(fullPath);
    foreach (QStandardItem *assetItem, assetItems) {
        QList<QStandardItem*> assetRow = m_assetsModel->takeRow(assetItem->row());
        while (!assetRow.isEmpty())
            delete assetRow.takeLast();
    }
Example #4
0
QString QWsServer::composeBadRequestResponse( QList<EWebsocketVersion> versions )
{
	QString response;
	
	response.append( QLatin1String("HTTP/1.1 400 Bad Request\r\n") );
	if ( ! versions.isEmpty() )
	{
		QString versionsStr = QString::number( (int)versions.takeLast() );
		int i = versions.size();
		while ( i-- )
		{
			versionsStr.append( QLatin1String(", ") + QString::number( (int)versions.takeLast() ) );
		}
		response.append( QLatin1String("Sec-WebSocket-Version: ") + versionsStr + QLatin1String("\r\n") );
	}

	return response;
}
Example #5
0
QVariantMap RmKeysOperation::rmKeys(const QVariantMap &map, const QStringList &removals)
{
    QVariantMap result = map;

    foreach (const QString &r, removals) {
        QList<QVariantMap> stack;

        const QStringList keys = r.split(QLatin1Char('/'));

        // Set up a stack of QVariantMaps along the path we take:
        stack.append(result);
        for (int i = 0; i < keys.count() - 1; ++i) {
            QVariantMap subMap;
            if (stack.last().contains(keys.at(i))) {
                subMap = stack.last().value(keys.at(i)).toMap();
            } else {
                std::cerr << "Warning: Key " << qPrintable(r) << " not found." << std::endl;
                continue;
            }
            stack.append(subMap);
        }

        // remove
        Q_ASSERT(stack.count() == keys.count());
        if (!stack.last().contains(keys.last())) {
            std::cerr << "Warning: Key " << qPrintable(r) << " not found." << std::endl;
            continue;
        }
        stack.last().remove(keys.last());

        // Generate new resultset by folding maps back in:
        QVariantMap foldBack = stack.takeLast();
        for (int i = keys.count() - 2; i >= 0; --i) { // skip last key, that is already taken care of
            const QString k = keys.at(i);
            QVariantMap current = stack.takeLast();
            current.insert(k, foldBack);
            foldBack = current;
        }

        Q_ASSERT(stack.count() == 0);
        Q_ASSERT(foldBack != map);

        result = foldBack;
    }
Example #6
0
void TabWidget::closeAllOtherActionTriggered()
{
    QAction* action = qobject_cast<QAction*>( QObject::sender() );

    QList<int> u = mUnityBrowserMap.uniqueKeys();
    int current = action->data().toInt();

    while( !u.isEmpty() )
    {
        int t = u.takeLast();
        if ( t != current ) removeUnityBrowser( t );
    }
}
Example #7
0
void WorkTabMgr::loadData(DataFileParser *file, bool closeOther)
{
    if(!file->seekToNextBlock("windowsInfo", 0))
        return;

    m_disable_window_close = true;

    startBatchOperation();

    int count = file->readVal<int>();

    if(!closeOther)
    {
        // use current window, if it is empty
        MainWindow *activeWin = dynamic_cast<MainWindow*>(qApp->activeWindow());
        if(activeWin && activeWin->onlyHomeTab())
        {
            activeWin->loadData(file);
            --count;
        }

        // create new windows
        for(int i = 0; i < count; ++i)
        {
            MainWindow *win = newWindow();
            win->loadData(file);
        }
    }
    else
    {
        QList<quint32> keys = m_windows.keys();
        while(count != m_windows.size())
        {
            if(count < m_windows.size())
            {
                m_windows[keys.back()]->close();
                m_windows.remove(keys.takeLast());
            }
            else
                newWindow();
        }

        for(WindowMap::iterator itr = m_windows.begin(); itr != m_windows.end(); ++itr)
            (*itr)->loadData(file);
    }

    m_disable_window_close = false;

    endBatchOperation();
}
void MColorListViewPrivate::updateColors()
{
    Q_Q(MColorListView);

    // A bit crude, perhaps, but let's conserve memory. this is called
    // relatively rarely anyway.
    if (buttonGroup) {
        int i = landscapePolicy->count() - 1;
        Q_ASSERT(landscapePolicy->count() == portraitPolicy->count());
        while (i >= 0) {
            landscapePolicy->removeAt(i--);
            portraitPolicy->removeAt(i--);
        }
        QList<MButton*> list = buttonGroup->buttons();
        while (!list.isEmpty()) {
            delete list.takeLast();
        }
        delete buttonGroup;
    }

    buttonGroup = new MButtonGroup();
    QObject::connect(buttonGroup, SIGNAL(buttonClicked(MButton*)),
                     q, SLOT(buttonClicked(MButton*)));

    const QColor &selectedColor = q->model()->selectedColor();

    int landColumns = 7;
    int portRows = 7;
    for (int i = 0; i < colors.size(); ++i) {
        SimpleColoredButton* button = new SimpleColoredButton(colors[i]);
        button->setStyleName("ColorSelectionButton");
        button->setCheckable(true);
        // We must check for selected color here too as the button has
        // to be checked *before* it is added to the group.
        if (colors[i] == selectedColor) {
            button->setChecked(true);
        }
        buttonGroup->addButton(button);
        // TODO: Calendar ALG defines that the color list should roll
        // horizontally in landscape mode (row by row), and vertically
        // in portraint mode (column by column). The implementation
        // here doesn't work nicely (for portrait) if we have more or
        // less colors than 28.
        landscapePolicy->addItem(button, i/landColumns, i%landColumns);
        portraitPolicy->addItem(button, i%portRows, i/portRows);
    }
}
bool DlgFileExplorer::DoAccept() {
    QList<cBaseMediaFile*> MediaList;
    ui->Browser->GetCurrentSelectedMediaFile(&MediaList);
    bool HaveFolder=false;
    bool Ret=true;
    for (int i=0;i<MediaList.count();i++) if (MediaList[i]->ObjectType==OBJECTTYPE_FOLDER) HaveFolder=true;
    if (MediaList.count()==0) Ret=false; else if (HaveFolder) {
        if (MediaList.count()==1) {
            ui->Browser->OpenFolder();
            Ret=false;
        } else {
            CustomMessageBox(this,QMessageBox::Information,windowTitle(),QApplication::translate("wgt_QMultimediaBrowser","The selection can't include folders."),QMessageBox::Ok,QMessageBox::Ok);
            Ret=false;
        }
    }
    while (!MediaList.isEmpty()) delete MediaList.takeLast();
    return Ret;
}
void PerfResourceCounterTest::testUnitSized()
{
    NoPayloadCounter::Container container;
    NoPayloadCounter counter(&container);
    QList<int> ids;
    for (int i = 0; i < 10000; ++i) {
        counter.request(1);
        int id = qrand();
        counter.obtain(id);
        ids.append(id);
        QCOMPARE(counter.currentTotal(), ids.length());
    }
    QCOMPARE(sum(container), counter.currentTotal());
    while (!ids.isEmpty()) {
        counter.release(ids.takeLast());
        QCOMPARE(counter.currentTotal(), ids.length());
    }
    QCOMPARE(sum(container), 0);
}
Example #11
0
float br::Evaluate(const QString &simmat, const QString &mask, const QString &csv)
{
    qDebug("Evaluating %s with %s", qPrintable(simmat), qPrintable(mask));

    const int Max_Points = 500;
    float result = -1;

    // Read files
    const Mat scores = BEE::readSimmat(simmat);
    File maskFile(mask); maskFile.insert("Size", scores.rows);
    const Mat masks = BEE::readMask(maskFile);
    if (scores.size() != masks.size()) qFatal("Simmat/Mask size mismatch.");

    // Make comparisons
    QList<Comparison> comparisons; comparisons.reserve(scores.rows*scores.cols);
    int genuineCount = 0, impostorCount = 0;
    for (int i=0; i<scores.rows; i++) {
        for (int j=0; j<scores.cols; j++) {
            const BEE::Mask_t mask_val = masks.at<BEE::Mask_t>(i,j);
            const BEE::Simmat_t simmat_val = scores.at<BEE::Simmat_t>(i,j);
            if (mask_val == BEE::DontCare) continue;
            comparisons.append(Comparison(simmat_val, j, i, mask_val == BEE::Match));
            if (comparisons.last().genuine) genuineCount++;
            else                            impostorCount++;
        }
    }

    if (genuineCount == 0) qFatal("No genuine scores.");
    if (impostorCount == 0) qFatal("No impostor scores.");

    qSort(comparisons);

    double genuineSum = 0, impostorSum = 0;
    QList<OperatingPoint> operatingPoints;
    QList<float> genuines, impostors;
    QVector<int> firstGenuineReturns(scores.rows, 0);

    int falsePositives = 0, previousFalsePositives = 0;
    int truePositives = 0, previousTruePositives = 0;
    int index = 0;
    while (index < comparisons.size()) {
        float thresh = comparisons[index].score;
        while ((index < comparisons.size()) &&
               (comparisons[index].score == thresh)) {
            const Comparison &comparison = comparisons[index];
            if (comparison.genuine) {
                truePositives++;
                genuineSum += comparison.score;
                genuines.append(comparison.score);
                if (firstGenuineReturns[comparison.query] < 1)
                    firstGenuineReturns[comparison.query] = abs(firstGenuineReturns[comparison.query]) + 1;
            } else {
                falsePositives++;
                impostorSum += comparison.score;
                impostors.append(comparison.score);
                if (firstGenuineReturns[comparison.query] < 1)
                    firstGenuineReturns[comparison.query]--;
            }
            index++;
        }

        if ((falsePositives > previousFalsePositives) &&
             (truePositives > previousTruePositives)) {
            // Restrict the extreme ends of the curve
            if ((falsePositives >= 10) && (falsePositives < impostorCount/2))
                operatingPoints.append(OperatingPoint(thresh, float(falsePositives)/impostorCount, float(truePositives)/genuineCount));
            previousFalsePositives = falsePositives;
            previousTruePositives = truePositives;
        }
    }

    if (operatingPoints.size() <= 2) qFatal("Insufficent genuines or impostors.");
    operatingPoints.takeLast(); // Remove point (1,1)

    // Write Metadata table
    QStringList lines;
    lines.append("Plot,X,Y");
    lines.append("Metadata,"+QString::number(scores.cols)+",Gallery");
    lines.append("Metadata,"+QString::number(scores.rows)+",Probe");
    lines.append("Metadata,"+QString::number(genuineCount)+",Genuine");
    lines.append("Metadata,"+QString::number(impostorCount)+",Impostor");
    lines.append("Metadata,"+QString::number(scores.cols*scores.rows-(genuineCount+impostorCount))+",Ignored");

    // Write DET, PRE, REC
    int points = qMin(operatingPoints.size(), Max_Points);
    for (int i=0; i<points; i++) {
        const OperatingPoint &operatingPoint = operatingPoints[double(i) / double(points-1) * double(operatingPoints.size()-1)];
        lines.append(QString("DET,%1,%2").arg(QString::number(operatingPoint.FAR),
                                              QString::number(1-operatingPoint.TAR)));
        lines.append(QString("FAR,%1,%2").arg(QString::number(operatingPoint.score),
                                              QString::number(operatingPoint.FAR)));
        lines.append(QString("FRR,%1,%2").arg(QString::number(operatingPoint.score),
                                              QString::number(1-operatingPoint.TAR)));
    }


    // Write FAR/TAR Bar Chart (BC)
    lines.append(qPrintable(QString("BC,0.001,%1").arg(QString::number(getTAR(operatingPoints, 0.001), 'f', 3))));
    lines.append(qPrintable(QString("BC,0.01,%1").arg(QString::number(result = getTAR(operatingPoints, 0.01), 'f', 3))));

    // Write SD & KDE
    points = qMin(qMin(Max_Points, genuines.size()), impostors.size());
    QList<double> sampledGenuineScores; sampledGenuineScores.reserve(points);
    QList<double> sampledImpostorScores; sampledImpostorScores.reserve(points);
    for (int i=0; i<points; i++) {
        const float genuineScore = genuines[double(i) / double(points-1) * double(genuines.size()-1)];
        const float impostorScore = impostors[double(i) / double(points-1) * double(impostors.size()-1)];
        lines.append(QString("SD,%1,Genuine").arg(QString::number(genuineScore)));
        lines.append(QString("SD,%1,Impostor").arg(QString::number(impostorScore)));
        sampledGenuineScores.append(genuineScore);
        sampledImpostorScores.append(impostorScore);
    }

    const double hGenuine = kernelDensityBandwidth(sampledGenuineScores);
    foreach (double f, sampledGenuineScores)
        lines.append(QString("KDEGenuine,%1,%2").arg(QString::number(f), QString::number(kernelDensityEstimation(sampledGenuineScores, f, hGenuine))));

    const double hImpostor = kernelDensityBandwidth(sampledImpostorScores);
    foreach (double f, sampledImpostorScores)
        lines.append(QString("KDEImpostor,%1,%2").arg(QString::number(f), QString::number(kernelDensityEstimation(sampledImpostorScores, f, hImpostor))));

    // Write Cumulative Match Characteristic (CMC) curve
    const int Max_Retrieval = 25;
    for (int i=1; i<=Max_Retrieval; i++) {
        int realizedReturns = 0, possibleReturns = 0;
        foreach (int firstGenuineReturn, firstGenuineReturns) {
            if (firstGenuineReturn > 0) possibleReturns++;
            if (firstGenuineReturn <= i) realizedReturns++;
        }
        lines.append(qPrintable(QString("CMC,%1,%2").arg(QString::number(i), QString::number(float(realizedReturns)/possibleReturns))));
    }

    if (!csv.isEmpty()) QtUtils::writeFile(csv, lines);
    qDebug("TAR @ FAR = 0.01: %.3f", result);
    return result;
}
QVector<QgsPoint> QgsSimplifyFeature::simplifyPoints( const QVector<QgsPoint>& pts, double tolerance )
{
  //just safety precaution
  if ( tolerance < 0 )
    return pts;
  // Douglas-Peucker simplification algorithm

  int anchor  = 0;
  int floater = pts.size() - 1;

  QList<StackEntry> stack;
  StackEntry temporary;
  StackEntry entry = {anchor, floater};
  stack.append( entry );

  QSet<int> keep;
  double anchorX;
  double anchorY;
  double seg_len;
  double max_dist;
  int farthest;
  double dist_to_seg;
  double vecX;
  double vecY;

  while ( !stack.empty() )
  {
    temporary = stack.takeLast();
    anchor = temporary.anchor;
    floater = temporary.floater;
    // initialize line segment
    if ( pts[floater] != pts[anchor] )
    {
      anchorX = pts[floater].x() - pts[anchor].x();
      anchorY = pts[floater].y() - pts[anchor].y();
      seg_len = sqrt( anchorX * anchorX + anchorY * anchorY );
      // get the unit vector
      anchorX /= seg_len;
      anchorY /= seg_len;
    }
    else
    {
      anchorX = anchorY = seg_len = 0.0;
    }
    // inner loop:
    max_dist = 0.0;
    farthest = anchor + 1;
    for ( int i = anchor + 1; i < floater; i++ )
    {
      dist_to_seg = 0.0;
      // compare to anchor
      vecX = pts[i].x() - pts[anchor].x();
      vecY = pts[i].y() - pts[anchor].y();
      seg_len = sqrt( vecX * vecX + vecY * vecY );
      // dot product:
      double proj = vecX * anchorX + vecY * anchorY;
      if ( proj < 0.0 )
      {
        dist_to_seg = seg_len;
      }
      else
      {
        // compare to floater
        vecX = pts[i].x() - pts[floater].x();
        vecY = pts[i].y() - pts[floater].y();
        seg_len = sqrt( vecX * vecX + vecY * vecY );
        // dot product:
        proj = vecX * ( -anchorX ) + vecY * ( -anchorY );
        if ( proj < 0.0 )
        {
          dist_to_seg = seg_len;
        }
        else
        {  // calculate perpendicular distance to line (pythagorean theorem):
          dist_to_seg = sqrt( qAbs( seg_len * seg_len - proj * proj ) );
        }
        if ( max_dist < dist_to_seg )
        {
          max_dist = dist_to_seg;
          farthest = i;
        }
      }
    }
    if ( max_dist <= tolerance )
    { // # use line segment
      keep.insert( anchor );
      keep.insert( floater );
    }
    else
    {
      StackEntry s = {anchor, farthest};
      stack.append( s );

      StackEntry r = {farthest, floater};
      stack.append( r );
    }
  }

  QList<int> keep2 = keep.toList();
  qSort( keep2 );

  QVector<QgsPoint> result;
  int position;
  while ( !keep2.empty() )
  {
    position = keep2.takeFirst();
    result.append( pts[position] );
  }
  return result;
}
Example #13
0
void MainWindow::on_step_execute_clicked()
{
    QList<int> loopStartIndex;
    // Clear all currently queued commands...
    stepperObj.clearAll();
    // (Re)queue all the commands in the stepper1 list...
    const char *currCmd;
    for (int i = 0; i < ui->step1_motionQueue->count(); i++) {
        // Queue a "move" command...
        if (ui->step1_motionQueue->item(i)->text().startsWith("move")) {
            currCmd = qPrintable(ui->step1_motionQueue->item(i)->text());
            double distance, duration;
            char str[100];
            sscanf(currCmd, "%s %lf %lf", str, &distance, &duration);
            std::cout << "Moving " << distance << " over " << duration << "\n";
            stepperObj.queueMoveCmd(0, distance, duration, 1.0);
        }
        else if (ui->step1_motionQueue->item(i)->text().startsWith("pause")) {
            currCmd = qPrintable(ui->step1_motionQueue->item(i)->text());
            double duration;
            char str[100];
            sscanf(currCmd, "%s %lf", str, &duration);
            std::cout << "Pausing for " << duration << "\n";
            stepperObj.queuePauseCmd(0, duration);
        }
        // Queue a "loop" command...
        else if (ui->step1_motionQueue->item(i)->text().startsWith("loop")) {
            currCmd = qPrintable(ui->step1_motionQueue->item(i)->text());
            int loopNum, numIters;
            char str[100];
            sscanf(currCmd, "%s %d %d", str, &loopNum, &numIters);
            std::cout << "Loop start command = " << i << "\n";
            loopStartIndex << i;
            stepperObj.queueLoopStartCmd(0);
        }
        // Queue an "endloop" command...
        else if (ui->step1_motionQueue->item(i)->text().startsWith("endloop")) {
            currCmd = qPrintable(ui->step1_motionQueue->item(i)->text());
            int loopNum, numIters;
            char str[100];
            sscanf(currCmd, "%s %d %d", str, &loopNum, &numIters);
            int startCmd = loopStartIndex.takeLast();
            std::cout << "Loopend starting cmd = " << startCmd << "\n";
            stepperObj.queueLoopEndCmd(0, startCmd, numIters);
        }
    }

    // (Re)queue all the commands in the stepper2 list...
    for (int i = 0; i < ui->step2_motionQueue->count(); i++) {
        // Queue a "move" command...
        if (ui->step2_motionQueue->item(i)->text().startsWith("move")) {
            currCmd = qPrintable(ui->step2_motionQueue->item(i)->text());
            double distance, duration;
            char str[100];
            sscanf(currCmd, "%s %lf %lf", str, &distance, &duration);
            std::cout << "Moving " << distance << " over " << duration << "\n";
            stepperObj.queueMoveCmd(1, distance, duration, 1.0);
        }
        else if (ui->step2_motionQueue->item(i)->text().startsWith("pause")) {
            currCmd = qPrintable(ui->step2_motionQueue->item(i)->text());
            double duration;
            char str[100];
            sscanf(currCmd, "%s %lf", str, &duration);
            std::cout << "Pausing for " << duration << "\n";
            stepperObj.queuePauseCmd(1, duration);
        }
        // Queue a "loop" command...
        else if (ui->step2_motionQueue->item(i)->text().startsWith("loop")) {
            currCmd = qPrintable(ui->step2_motionQueue->item(i)->text());
            int loopNum, numIters;
            char str[100];
            sscanf(currCmd, "%s %d %d", str, &loopNum, &numIters);
            std::cout << "Loop start command = " << i << "\n";
            loopStartIndex << i;
            stepperObj.queueLoopStartCmd(1);
        }
        // Queue an "endloop" command...
        else if (ui->step2_motionQueue->item(i)->text().startsWith("endloop")) {
            currCmd = qPrintable(ui->step2_motionQueue->item(i)->text());
            int loopNum, numIters;
            char str[100];
            sscanf(currCmd, "%s %d %d", str, &loopNum, &numIters);
            int startCmd = loopStartIndex.takeLast();
            std::cout << "Loopend starting cmd = " << startCmd << "\n";
            stepperObj.queueLoopEndCmd(1, startCmd, numIters);
        }
    }
    // And start...
    stepperObj.startAll();
}
Example #14
0
void QgsEffectStack::draw( QgsRenderContext &context )
{
  QPainter* destPainter = context.painter();

  //first, we build up a list of rendered effects
  //we do this moving backwards through the stack, so that each effect's results
  //becomes the source of the previous effect
  QPicture* sourcePic = new QPicture( *source() );
  QPicture* currentPic = sourcePic;
  QList< QPicture* > results;
  for ( int i = mEffectList.count() - 1; i >= 0; --i )
  {
    QgsPaintEffect* effect = mEffectList[i];
    if ( !effect->enabled() )
    {
      continue;
    }

    QPicture* pic;
    if ( effect->type() == "drawSource" )
    {
      //draw source is always the original source, regardless of previous effect results
      pic = sourcePic;
    }
    else
    {
      pic = currentPic;
    }

    QPicture *resultPic = new QPicture();
    QPainter p( resultPic );
    context.setPainter( &p );
    //effect stack has it's own handling of the QPicture DPI issue, so
    //we disable QgsPaintEffect's internal workaround
    effect->requiresQPainterDpiFix = false;
    effect->render( *pic, context );
    effect->requiresQPainterDpiFix = true;
    p.end();

    results << resultPic;
    if ( mEffectList[i]->drawMode() != QgsPaintEffect::Render )
    {
      currentPic = resultPic;
    }
  }
  delete sourcePic;
  sourcePic = 0;

  context.setPainter( destPainter );
  //then, we render all the results in the opposite order
  for ( int i = 0; i < mEffectList.count(); ++i )
  {
    if ( !mEffectList[i]->enabled() )
    {
      continue;
    }

    QPicture* pic = results.takeLast();
    if ( mEffectList[i]->drawMode() != QgsPaintEffect::Modifier )
    {
      context.painter()->save();
      fixQPictureDpi( context.painter() );
      context.painter()->drawPicture( 0, 0, *pic );
      context.painter()->restore();

    }
    delete pic;
  }
}
Example #15
0
void GameRule::onPhaseChange(ServerPlayer *player) const{
    Room *room = player->getRoom();
    switch(player->getPhase()){
    case Player::RoundStart:{
            break;
        }
    case Player::Start: {
            player->setMark("SlashCount", 0);

            if(room->getMode() == "05_2v3")
                if(player->isLord() || player->getRole() == "loyalist"){
                    int card_id = room->drawCard();
                    room->showCard(player, card_id);
                    room->getThread()->delay();
                    player->addToPile("Angers", card_id);
                    LogMessage log;
                    log.type = "$Juqi";
                    log.from = player;
                    log.card_str = QString::number(card_id);
                    room->sendLog(log);
                    if(player->getPile("Angers").length() > 4){
                        const QList<int> angs = player->getPile("Angers");
                        room->fillAG(angs, player);
                        int card_id = room->askForAG(player, angs, false, "cbangercollect");
                        if(card_id < 0)
                            card_id = player->getPile("Angers").first();
                        room->throwCard(card_id);
                        player->invoke("clearAG");
                    }
                }

            break;
        }
    case Player::Judge: {
            QList<const DelayedTrick *> tricks = player->delayedTricks();
            while(!tricks.isEmpty() && player->isAlive()){
                const DelayedTrick *trick = tricks.takeLast();
                bool on_effect = room->cardEffect(trick, NULL, player);
                if(!on_effect)
                    trick->onNullified(player);
            }

            break;
        }
    case Player::Draw: {
            int nUm = 2;
            if(room->getTag("FirstRound").toBool()){
                room->setTag("FirstRound", false);
                if(room->getMode() == "02_1v1")
                    nUm --;
            }

            QVariant num = nUm;
            room->getThread()->trigger(DrawNCards, player, num);
            int n = num.toInt();
            if(n > 0)
                player->drawCards(n, false);
            room->getThread()->trigger(DrawNCardsDone, player, num);
            break;
        }

    case Player::Play: {
            player->clearHistory();

            while(player->isAlive()){
                CardUseStruct card_use;
                room->activate(player, card_use);
                if(card_use.isValid()){
                    room->useCard(card_use);
                }else
                    break;
            }
            break;
        }

    case Player::Discard:{
            int discard_num = player->getHandcardNum() - player->getMaxCards();
            if(player->hasFlag("jilei")){
                QSet<const Card *> jilei_cards;
                QList<const Card *> handcards = player->getHandcards();
                foreach(const Card *card, handcards){
                    if(player->isJilei(card))
                        jilei_cards << card;
                }

                if(jilei_cards.size() > player->getMaxCards()){
                    // show all his cards
                    room->showAllCards(player);

                    DummyCard *dummy_card = new DummyCard;
                    foreach(const Card *card, handcards.toSet() - jilei_cards){
                        dummy_card->addSubcard(card);
                    }
                    room->throwCard(dummy_card, player);

                    return;
                }
            }

            if(discard_num > 0)
                room->askForDiscard(player, "gamerule", discard_num);
            break;
        }
Example #16
0
void GameRule::onPhaseChange(ServerPlayer *player) const{
    Room *room = player->getRoom();
    switch(player->getPhase()){
    case Player::RoundStart:{
            break;
        }
    case Player::Start: {
            player->setMark("SlashCount", 0);
            break;
        }
    case Player::Judge: {
            QList<const DelayedTrick *> tricks = player->delayedTricks();
            while(!tricks.isEmpty() && player->isAlive()){
                const DelayedTrick *trick = tricks.takeLast();
                bool on_effect = room->cardEffect(trick, NULL, player);
                if(!on_effect)
                    trick->onNullified(player);
            }

            break;
        }
    case Player::Draw: {
            QVariant num = 2;
            if(room->getTag("FirstRound").toBool()){
                room->setTag("FirstRound", false);
                if(room->getMode() == "02_1v1")
                    num = 1;
            }

            room->getThread()->trigger(DrawNCards, room, player, num);
            int n = num.toInt();
            if(n > 0)
                player->drawCards(n, false);

            break;
        }

    case Player::Play: {
            while(player->isAlive()){
                CardUseStruct card_use;
                room->activate(player, card_use);
                if(card_use.isValid()){
                    room->useCard(card_use);
                }else
                    break;
            }

            break;
        }

    case Player::Discard:{
        while (player->getHandcardNum() > player->getMaxCards())
        {
            int discard_num = player->getHandcardNum() - player->getMaxCards();
            if(player->hasFlag("jilei")){
                QSet<const Card *> jilei_cards;
                QList<const Card *> handcards = player->getHandcards();
                foreach(const Card *card, handcards){
                    if(player->isJilei(card))
                        jilei_cards << card;
                }

                if(jilei_cards.size() > player->getMaxCards()){
                    // show all his cards
                    room->showAllCards(player);

                    DummyCard *dummy_card = new DummyCard;
                    foreach(const Card *card, handcards.toSet() - jilei_cards){
                        dummy_card->addSubcard(card);
                    }
                    room->throwCard(dummy_card, player);

                    return;
                }
            }

            if(discard_num > 0)
                room->askForDiscard(player, "gamerule", discard_num, 1);
        }
        break;
    }