Пример #1
0
QList<QList<card> > Method::FindHand(Hand hand, bool beat)
{
    HandType handType = hand.getHandType();
    CardPoint basePoint = CardPoint(hand.getBasePoint());
    int extra = hand.getExtra();

    if (handType == Hand_Pass)
    {}
    else if (handType == Hand_Single)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point < Card_End; point = CardPoint(point + 1))
        {
            QList<card> findCards = FindSamePointCards(point, 1);
            if (!findCards.isEmpty())
            {
                findCardsArray.append(findCards);
            }
        }
        return findCardsArray;
    }
    else if (handType == Hand_Pair)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point < Card_End; point = CardPoint(point + 1))
        {
            QList<card> findCards = FindSamePointCards(point, 2);
            if (!findCards.isEmpty())
            {
                findCardsArray.append(findCards);
            }
        }

        return findCardsArray;
    }
    else if (handType == Hand_Triple)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point < Card_End; point = CardPoint(point + 1))
        {
            QList<card> findCards = FindSamePointCards(point, 3);
            if (!findCards.isEmpty())
            {
                findCardsArray.append(findCards);
            }
        }

        return findCardsArray;
    }
    else if (handType == Hand_Triple_Single)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point < Card_End; point = CardPoint(point + 1))
        {
            QList<card> findCards = FindSamePointCards(point, 3);
            if (!findCards.isEmpty())
            {
                findCardsArray.append(findCards);
            }
        }

        if (!findCardsArray.isEmpty())
        {
            QList<card> remainCards = m_cards;
            for(int i=0;i<findCardsArray.size();i++)
            {
                for(int j=0;j<findCardsArray[i].size();j++)
                    remainCards.removeOne((findCardsArray[i])[j]);
            }
            //remainCards.Remove(findCardsArray);

            Method st(m_player, remainCards);
            QList<QList<card> > oneCardsArray = st.FindHand(Hand(Hand_Single, Card_Begin, 0), false);
            if (!oneCardsArray.isEmpty())
            {
                for (int i = 0; i < findCardsArray.size(); i++)
                {
                    findCardsArray[i] .append(oneCardsArray[0]);
                }
            }
            else
            {
                findCardsArray.clear();
            }
        }

        return findCardsArray;
    }
    else if (handType == Hand_Triple_Pair)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point < Card_End; point = CardPoint(point + 1))
        {
            QList<card>  findCards = FindSamePointCards(point, 3);
            if (!findCards.isEmpty())
            {
                findCardsArray << findCards;
            }
        }

        if (!findCardsArray.isEmpty())
        {
            QList<card>  remainCards = m_cards;
            for(int i=0;i<findCardsArray.size();i++)
                for(int j=0;j<findCardsArray[i].size();j++)
                    remainCards.removeOne(findCardsArray[i][j]);

            //            remainCards.Remove(findCardsArray);

            Method st(m_player, remainCards);
            QList<QList<card> > pairCardsArray = st.FindHand(Hand(Hand_Pair, Card_Begin, 0), false);
            if (!pairCardsArray.isEmpty())
            {
                for (int i = 0; i < findCardsArray.size(); i++)
                {
                    findCardsArray[i].append(pairCardsArray[0]);
                }
            }
            else
            {
                findCardsArray.clear();
            }
        }

        return findCardsArray;
    }
    else if (handType == Hand_Plane)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point <= Card_K; point = CardPoint(point + 1))
        {
            QList<card>  prevCards = FindSamePointCards(point, 3);
            QList<card>  nextCards = FindSamePointCards(CardPoint(point+1), 3);
            if (!prevCards.isEmpty() && !nextCards.isEmpty())
            {
                findCardsArray.append(prevCards);
                findCardsArray.append(nextCards);
            }
        }
    }
    else if (handType == Hand_Plane_Two_Single)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point <= Card_K; point = CardPoint(point + 1))
        {
            QList<card>  prevCards = FindSamePointCards(point, 3);
            QList<card>  nextCards = FindSamePointCards(CardPoint(point+1), 3);
            if (!prevCards.isEmpty() && !nextCards.isEmpty())
            {
                QList<card>  findCards;

                findCards.append(prevCards);
                findCards.append(nextCards);
                findCardsArray.append(findCards);
            }
        }

        if (!findCardsArray.isEmpty())
        {
            QList<card>  remainCards = m_cards;
            for(int i=0;i<findCardsArray.size();i++)
            {
                for(int j=0;j<findCardsArray[i].size();j++)
                    remainCards.removeOne((findCardsArray[i])[j]);
            }

            Method st(m_player, remainCards);
            QList<QList<card> > oneCardsArray = st.FindHand(Hand(Hand_Single, Card_Begin, 0), false);
            if (oneCardsArray.size() >= 2)
            {
                for (int i = 0; i < findCardsArray.size(); i++)
                {
                    QList<card>  oneCards;
                    oneCards.append(oneCardsArray[0]);
                    oneCards.append(oneCardsArray[1]);
                    findCardsArray[i] << oneCards;
                }
            }
            else
            {
                findCardsArray.clear();
            }
        }

        return findCardsArray;
    }
    else if (handType == Hand_Plane_Two_Pair)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point <= Card_K; point = CardPoint(point + 1))
        {
            QList<card>  prevCards = FindSamePointCards(point, 3);
            QList<card>  nextCards = FindSamePointCards(CardPoint(point+1), 3);
            if (!prevCards.isEmpty() && !nextCards.isEmpty())
            {
                QList<card>  findCards;
                findCards << prevCards << nextCards;
                findCardsArray << findCards;
            }
        }

        if (!findCardsArray.isEmpty())
        {
            QList<card>  remainCards = m_cards;
            for(int i=0;i<findCardsArray.size();i++)
            {
                for(int j=0;j<findCardsArray[i].size();j++)
                    remainCards.removeOne((findCardsArray[i])[j]);
            }

            Method st(m_player, remainCards);
            QList<QList<card> > pairCardsArray = st.FindHand(Hand(Hand_Pair, Card_Begin, 0), false);
            if (pairCardsArray.size() >= 2)
            {
                for (int i = 0; i < findCardsArray.size(); i++)
                {
                    QList<card>  pairCards;
                    pairCards << pairCardsArray[0] << pairCardsArray[1];
                    findCardsArray[i] << pairCards;
                }
            }
            else
            {
                findCardsArray.clear();
            }
        }

        return findCardsArray;
    }
    else if (handType == Hand_Seq_Pair)
    {
        if (beat)
        {
            QList<QList<card> > findCardsArray;
            for (CardPoint point = CardPoint(basePoint + 1); point <= Card_Q; point = CardPoint(point + 1))
            {
                bool seqPairFound = true;
                QList<card>  seqPair;

                for (int i = 0; i < extra; i++)
                {
                    QList<card>  cards = FindSamePointCards(CardPoint(point + i), 2);
                    if (cards.isEmpty() || (point + i >= Card_2))	// 连对中断,或顶到2了
                    {
                        seqPairFound = false;
                        seqPair.clear();
                        break;
                    }
                    else
                    {
                        seqPair << cards;
                    }
                }

                if (seqPairFound)
                {
                    findCardsArray << seqPair;
                    return findCardsArray;
                }
            }

            return findCardsArray;
        }
        else
        {
            QList<QList<card> > findCardsArray;

            for (CardPoint point = Card_3; point <= Card_Q; point = CardPoint(point + 1))
            {
                QList<card>  cards0 = FindSamePointCards(point, 2);
                QList<card>  cards1 = FindSamePointCards(CardPoint(point + 1), 2);
                QList<card>  cards2 = FindSamePointCards(CardPoint(point + 2), 2);

                if (cards0.isEmpty() || cards1.isEmpty() || cards2.isEmpty()) continue;

                QList<card>  baseSeq;
                baseSeq << cards0 << cards1 << cards2;
                findCardsArray << baseSeq;

                int followed = 3;
                QList<card>  alreadyFollowedCards;

                while (true)
                {
                    CardPoint followedPoint = CardPoint(point + followed);
                    if (followedPoint >= Card_2)
                    {
                        break;
                    }

                    QList<card>  followedCards = FindSamePointCards(followedPoint, 2);
                    if (followedCards.isEmpty())
                    {
                        break;
                    }
                    else
                    {
                        alreadyFollowedCards << followedCards;
                        QList<card>  newSeq = baseSeq;
                        newSeq << alreadyFollowedCards;

                        findCardsArray << newSeq;
                        followed++;
                    }
                }
            }

            return findCardsArray;
        }
    }
    else if (handType == Hand_Seq_Single)
    {
        if (beat)
        {
            QList<QList<card> > findCardsArray;
            for (CardPoint point = CardPoint(basePoint + 1); point <= Card_10; point = CardPoint(point + 1))
            {
                bool seqSingleFound = true;
                QList<card>  seqSingle;

                for (int i = 0; i < extra; i++)
                {
                    QList<card>  cards = FindSamePointCards(CardPoint(point + i), 1);
                    if (cards.isEmpty() || (point + extra >= Card_2))
                    {
                        seqSingleFound = false;
                        seqSingle.clear();
                        break;
                    }
                    else
                    {
                        seqSingle << cards;
                    }
                }

                if (seqSingleFound)
                {
                    findCardsArray << seqSingle;
                    return findCardsArray;
                }
            }
        }
        else
        {
            QList<QList<card> > findCardsArray;

            for (CardPoint point = Card_3; point <= Card_10; point = CardPoint(point + 1))
            {
                QList<card>  cards0 = FindSamePointCards(point, 1);
                QList<card>  cards1 = FindSamePointCards(CardPoint(point + 1), 1);
                QList<card>  cards2 = FindSamePointCards(CardPoint(point + 2), 1);
                QList<card>  cards3 = FindSamePointCards(CardPoint(point + 3), 1);
                QList<card>  cards4 = FindSamePointCards(CardPoint(point + 4), 1);

                if (cards0.isEmpty() || cards1.isEmpty() || cards2.isEmpty()
                        || cards3.isEmpty() || cards4.isEmpty())
                {
                    continue;
                }

                QList<card>  baseSeq;
                baseSeq << cards0 << cards1 << cards2 << cards3 << cards4;
                findCardsArray << baseSeq;

                int followed = 5;
                QList<card>  alreadyFollowedCards;

                while (true)
                {
                    CardPoint followedPoint = CardPoint(point + followed);
                    if (followedPoint >= Card_2)
                    {
                        break;
                    }

                    QList<card>  followedCards = FindSamePointCards(followedPoint, 1);
                    if (followedCards.isEmpty())
                    {
                        break;
                    }
                    else
                    {
                        alreadyFollowedCards << followedCards;
                        QList<card>  newSeq = baseSeq;
                        newSeq << alreadyFollowedCards;

                        findCardsArray << newSeq;
                        followed++;
                    }
                }
            }

            return findCardsArray;
        }
    }
    else if (handType == Hand_Bomb)
    {
        QList<QList<card> > findCardsArray;

        CardPoint beginPoint = beat ? CardPoint(basePoint + 1) : CardPoint(Card_Begin + 1);
        for (CardPoint point = beginPoint; point < Card_End; point = CardPoint(point + 1))
        {
            QList<card>  findCards = FindSamePointCards(point, 4);
            if (!findCards.isEmpty())
            {
                findCardsArray << findCards;
            }
        }

        return findCardsArray;
    }

    QList<QList<card> > c;
    c.clear();
    return c;
}
Пример #2
0
QList<card> Method::PlayBeatHand(Hand hand)
{
    // 先固定住最优顺子,从余下牌中打出
    QList<card>  left = m_cards;
    QList<QList<card> > cardlll=Method(m_player,left).PickOptimalSeqSingles();
    for(int i=0;i<cardlll.size();i++)
        for(int j=0;j<cardlll[i].size();j++ )
            left.removeOne(cardlll[i][j]);

    //left.Remove(Method(m_player, left).PickOptimalSeqSingles());

    if (hand.getHandType() == Hand_Single)	// 如果压单牌,尽量从单张牌中挑
    {
        QList<QList<card> > singleArray = Method(m_player, left).FindCardsByCount(1);
        for (int i = 0; i < singleArray.size(); i++)
        {
            if (Hand(singleArray[i]).Defeat(hand))
            {
                return singleArray[i];
            }
        }
    }
    else if (hand.getHandType() == Hand_Pair)	// 如果压双牌,尽量从双牌中挑
    {
        QList<QList<card> > pairArray = Method(m_player, left).FindCardsByCount(2);
        for (int i = 0; i < pairArray.size(); i++)
        {
            if (Hand(pairArray[i]).Defeat(hand))
            {
                return pairArray[i];
            }
        }
    }

    Player* nextPlayer = m_player->getNextPlayer();
    QList<QList<card> > beatCardsArray = Method(m_player, left).FindHand(hand, true);
    if (!beatCardsArray.isEmpty())
    {
        if (m_player->getRole() != nextPlayer->getRole() &&
                nextPlayer->getCards().size() <= 2)
        {
            return beatCardsArray.back();
        }
        else
        {
            return beatCardsArray.front();
        }
    }
    else	// 余下牌没法打时,只好从顺子中挑牌
    {
        beatCardsArray = Method(m_player, m_cards).FindHand(hand, true);
        if (!beatCardsArray.isEmpty())
        {
            if (m_player->getRole() != nextPlayer->getRole() &&
                    nextPlayer->getCards().size() <= 2)
            {
                return beatCardsArray.back();
            }
            else
            {
                return beatCardsArray.front();
            }
        }
    }

    // 对家剩牌小于3张,有炸则炸
    Player* hitPlayer = m_player->getHitPlayer();
    if (m_player->getRole() != hitPlayer->getRole())
    {
        if (hitPlayer->getCards().size() <= 3)
        {
            QList<QList<card> > bombs = FindCardsByCount(4);
            if (!bombs.isEmpty())
            {
                return bombs[0];
            }
        }
    }

    QList<card>  empty;
    empty.clear();
    return empty;
}
Пример #3
0
int main(int argc, const char * argv[])
{
    Deck deck;
    Player *player = player_factory(argv[3]);
    Hand hand;
    
    cout << "Shuffling the deck\n";
    for (int counter = 0; counter < 7; counter++) {
        int num = get_cut();
        cout << "cut at " << num << endl;
        deck.shuffle(num);
        player->shuffled();
    }
    
    int minBet = 5;
    int bankroll = atoi(argv[1]);
    int totalHands = atoi(argv[2]);
    int handsPlayed = 1;
    
    while ((bankroll >= minBet) & (handsPlayed <= totalHands)) {
        cout << "Hand " << handsPlayed << " bankroll " << bankroll << endl;
        if (deck.cards_remaining() < 20) {
            int cutNum = get_cut();
            cout << "cut at " << cutNum << endl;
            deck.shuffle(cutNum);
            player->shuffled();
        }
        
        
        int wager = player->bet(bankroll, minBet);
        cout << "Player bets " << wager << endl;

        Hand dealerHand;
        
        Card p1;
        Card p2;
        Card d1;
        Card d2;
        p1 = deck.deal();
        d1 = deck.deal();
        p2 = deck.deal();
        d2 = deck.deal();
        hand.add_card(p1);
        hand.add_card(p2);
        dealerHand.add_card(d1);
        dealerHand.add_card(d2);
        
        cout << "Player dealt " << p1 << endl;
        player->expose(p1);
        cout << "Dealer dealt " << d1 << endl;
        player->expose(d1);
        cout << "Player dealt " << p2 << endl;
        player->expose(p2);
        
        if (hand.hand_value() == 21) {
            bankroll += (3/2)*wager;
            cout << "Player dealt natural 21\n";
            handsPlayed++;
            hand.discard_all();
        } else {
        
        cout << "Player's total is " << hand.hand_value() << endl;
        while (player->draw(d1, hand)) {
            Card c1 = deck.deal();
            hand.add_card(c1);
            player->expose(c1);
            cout << "Player dealt " << c1 << endl;
            cout << "Player's total is " << hand.hand_value() << endl;
        }
        
        if ((hand.hand_value() > 21) & (!hand.hand_is_soft())) {
            cout << "Player busts!" << endl;
            bankroll -= wager;
            handsPlayed++;
            hand.discard_all();
        } else {
            cout << "Dealer's hole card is " << d2 << endl;
            player->expose(d2);
            
            while (dealerHand.hand_value() < 17) {
                Card c1 = deck.deal();
                dealerHand.add_card(c1);
                player->expose(c1);
                cout << "Dealer dealt " << c1 << endl;
            }
            cout << "Dealer's total is " << dealerHand.hand_value() << endl;
        
            if ((dealerHand.hand_value() > 21) & (!dealerHand.hand_is_soft())) {
                cout << "Dealer busts!" << endl;
                bankroll += wager;
                handsPlayed++;
                hand.discard_all();
            } else {
        
                if (dealerHand.hand_value() > hand.hand_value()) {
                    cout << "Dealer wins\n";
                    bankroll -= wager;
                    handsPlayed++;
                    hand.discard_all();
                } else if (dealerHand.hand_value() < hand.hand_value()) {
                    cout << "Player wins\n";
                    bankroll += wager;
                    handsPlayed++;
                    hand.discard_all();
                } else {
                    cout << "Push\n";
                    handsPlayed++;
                    hand.discard_all();
                }
            }
        }
    }
}
    
    cout << "Player has " << bankroll << " after " << handsPlayed-1 << " hands\n";
}
Пример #4
0
static void setPalm(float deltaTime, int index) {
    MyAvatar* avatar = Application::getInstance()->getAvatar();
    Hand* hand = avatar->getHand();
    PalmData* palm;
    bool foundHand = false;
    for (size_t j = 0; j < hand->getNumPalms(); j++) {
        if (hand->getPalms()[j].getSixenseID() == index) {
            palm = &(hand->getPalms()[j]);
            foundHand = true;
        }
    }
    if (!foundHand) {
        PalmData newPalm(hand);
        hand->getPalms().push_back(newPalm);
        palm = &(hand->getPalms()[hand->getNumPalms() - 1]);
        palm->setSixenseID(index);
    }
    
    palm->setActive(true);
    
    // Read controller buttons and joystick into the hand
    const QString PRIO_JOYSTICK_NAME = "PrioVR";
    Joystick* prioJoystick = JoystickScriptingInterface::getInstance().joystickWithName(PRIO_JOYSTICK_NAME);
    if (prioJoystick) {
        const QVector<float> axes = prioJoystick->getAxes();
        const QVector<bool> buttons = prioJoystick->getButtons();
        
        if (axes.size() >= 4 && buttons.size() >= 4) {
            if (index == LEFT_HAND_INDEX) {
                palm->setControllerButtons(buttons[1] ? BUTTON_FWD : 0);
                palm->setTrigger(buttons[0] ? 1.0f : 0.0f);
                palm->setJoystick(axes[0], -axes[1]);
                
            } else {
                palm->setControllerButtons(buttons[3] ? BUTTON_FWD : 0);
                palm->setTrigger(buttons[2] ? 1.0f : 0.0f);
                palm->setJoystick(axes[2], -axes[3]);
            }
        }
    }
    
    // NOTE: this math is done in the worl-frame with unecessary complexity.
    // TODO: transfom this to stay in the model-frame.
    glm::vec3 position;
    glm::quat rotation;
    SkeletonModel* skeletonModel = &Application::getInstance()->getAvatar()->getSkeletonModel();
    int jointIndex;
    glm::quat inverseRotation = glm::inverse(Application::getInstance()->getAvatar()->getOrientation());
    if (index == LEFT_HAND_INDEX) {
        jointIndex = skeletonModel->getLeftHandJointIndex();
        skeletonModel->getJointRotationInWorldFrame(jointIndex, rotation);      
        rotation = inverseRotation * rotation * glm::quat(glm::vec3(0.0f, PI_OVER_TWO, 0.0f));
        
    } else {
        jointIndex = skeletonModel->getRightHandJointIndex();
        skeletonModel->getJointRotationInWorldFrame(jointIndex, rotation);
        rotation = inverseRotation * rotation * glm::quat(glm::vec3(0.0f, -PI_OVER_TWO, 0.0f));
    }
    skeletonModel->getJointPositionInWorldFrame(jointIndex, position);
    position = inverseRotation * (position - skeletonModel->getTranslation());
    
    palm->setRawRotation(rotation);
    
    //  Compute current velocity from position change
    glm::vec3 rawVelocity;
    if (deltaTime > 0.0f) {
        rawVelocity = (position - palm->getRawPosition()) / deltaTime; 
    } else {
        rawVelocity = glm::vec3(0.0f);
    }
    palm->setRawVelocity(rawVelocity);
    palm->setRawPosition(position);
    
    // Store the one fingertip in the palm structure so we can track velocity
    const float FINGER_LENGTH = 0.3f;   //  meters
    const glm::vec3 FINGER_VECTOR(0.0f, 0.0f, FINGER_LENGTH);
    const glm::vec3 newTipPosition = position + rotation * FINGER_VECTOR;
    glm::vec3 oldTipPosition = palm->getTipRawPosition();
    if (deltaTime > 0.0f) {
        palm->setTipVelocity((newTipPosition - oldTipPosition) / deltaTime);
    } else {
        palm->setTipVelocity(glm::vec3(0.0f));
    }
    palm->setTipPosition(newTipPosition);
}
Пример #5
0
void QTVS_Leap::HandLogic()
{
  //TODO: Fix this
  if (hands.count() == 1)
  {
    int iHandToFingerShift = hand.isLeft() ? 5 : 0;

    for (int iFingerCounter = iHandToFingerShift;
         iFingerCounter <= iHandToFingerShift + 4;
         iFingerCounter ++)
      QCoreApplication::postEvent(fingerTraces.at(iFingerCounter), new QHideEvent());

    iHandToFingerShift = hand.isLeft() ? 0 : 5;

if(ui.checkBox_ShowFingers->isChecked())
{
    for (int iFingerCounter = iHandToFingerShift;
         iFingerCounter <= iHandToFingerShift + 4;
         iFingerCounter ++)
      QCoreApplication::postEvent(fingerTraces.at(iFingerCounter), new QShowEvent());
}

  }
  else if (hands.isEmpty())
  {
    foreach (FingerTraceWindow * fTrace, fingerTraces)
      QCoreApplication::postEvent(fTrace, new QHideEvent());
    // QCoreApplication::postEvent(thumbTrace, new QHideEvent());
    // QCoreApplication::postEvent(indexTrace, new QHideEvent());
    // QCoreApplication::postEvent(middleTrace, new QHideEvent());
    // QCoreApplication::postEvent(ringTrace, new QHideEvent());
    // QCoreApplication::postEvent(pinkieTrace, new QHideEvent());
  }
  else
  {
    if(ui.checkBox_ShowFingers->isChecked())
    {
    foreach (FingerTraceWindow * fTrace, fingerTraces)
      QCoreApplication::postEvent(fTrace, new QShowEvent());      
    }
    // QCoreApplication::postEvent(thumbTrace, new QShowEvent());
    // QCoreApplication::postEvent(indexTrace, new QShowEvent());
    // QCoreApplication::postEvent(middleTrace, new QShowEvent());
    // QCoreApplication::postEvent(ringTrace, new QShowEvent());
    // QCoreApplication::postEvent(pinkieTrace, new QShowEvent());

  }

  for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
    // Get the first hand
    hand = *hl;

//TODO: Perhaps move this to gestures?
    if (ui.checkBox_Crunch->isChecked())
    {
      if (hands.count() == 2)
      {
        // we check if one hand's dragging and the other's closed
        if (hand.isLeft())
        {
          // if this hand is left, and the other hand (right) is dragging something..
          if (debugWindowDrag_Right.left != -1)
          {
            debugDisplayString = QString::number(hand.grabStrength());
            //pretty much closed
            if (hand.grabStrength() >= 0.7)
            {
              SendMessage(debugWindowHWND_Right, WM_SYSCOMMAND, SC_CLOSE, 0);
              // DestroyWindow();
            }
          }
        }
        else
        {
          // if this hand is left, and the other hand (right) is dragging something..
          if (debugWindowDrag_Left.left != -1)
          {
            //pretty much closed
            if (hand.grabStrength() >= 0.7)
            {
              // DestroyWindow(debugWindowHWND_Left);
              SendMessage(debugWindowHWND_Left, WM_SYSCOMMAND, SC_CLOSE, 0);
            }
          }
        }
      }
    }
    // std::string handType = hand.isLeft() ? "Left hand" : "Right hand";

    // std::cout << std::string(2, ' ') << handType << ", id: " << hand.id()
    //           << ", palm position: " << hand.palmPosition() << std::endl;
    // Get the hand's normal vector and direction
    const Vector normal = hand.palmNormal();
    const Vector direction = hand.direction();

    // Calculate the hand's pitch, roll, and yaw angles
    // debugDisplayString = QString(", palm position: " + QString(hand.palmPosition().toString().data() ));

    // debugDisplayString = QString::number(hand.palmPosition().x); //20
    // debugDisplayString.append("\n");
    // debugDisplayString.append(QString::number(hand.palmPosition().y)); // 5
    // debugDisplayString.append("\n");
    // debugDisplayString.append(QString::number(hand.palmPosition().z));
    // debugDisplayString.append("\n");
    // debugDisplayString.append("roll:" + QString::number(normal.roll()));
///--------------------------------------------------

    if (debug_extendedFingerCounter != 0 && ui.checkBox_palmMouse->isChecked())
      HandCursorPosition(hand.stabilizedPalmPosition());


    if (ui.checkBox_HandRollDrag->isChecked())
    {
      if (bDebug_HandRollDrag)
      {
        if (normal.roll() > 0.7)
        {
          bDebug_HandRollDrag = false;

          if (debug_extendedFingerCounter != 0)
            MouseKeyboardEmulation::MouseLeftClickDown();
        }
      }
    }
    if (!bDebug_HandRollDrag)
    {
      if (normal.roll() < 0.5)
      {
        bDebug_HandRollDrag = true;
        MouseKeyboardEmulation::MouseLeftClickUp();
      }
    }

///-----------------------------------------------

    debug_extendedFingerCounter = 0;
    foreach (Finger finger, fingers)
    {
      if (finger.isExtended())
        debug_extendedFingerCounter++;
    }

    // Fist Scrolling

    if (debug_extendedFingerCounter == 0 && ui.checkBox_palmScroll->isChecked())
    {

      if (fFistPositionY == 0)
        fFistPositionY = hand.palmPosition().y;


      if (hand.palmPosition().y > fFistPositionY + 10)
      {
        float fDifference = hand.palmPosition().y - fFistPositionY + 10;
        fDifference /= 10;
        MouseKeyboardEmulation::MouseWheelUp(fDifference);
      }
      else if (hand.palmPosition().y < fFistPositionY - 10)
      {
        float fDifference = abs(hand.palmPosition().y - fFistPositionY - 10);
        fDifference /= 10;
        MouseKeyboardEmulation::MouseWheelUp(-1 * fDifference);
      }

      //              debugDisplayString = QString::number(ThumbMiddleDifference_X); //20
      //    debugDisplayString.append("\n");
      //       debugDisplayString.append(QString::number(abs(middleFinger.stabilizedTipPosition().y - indexFinger.stabilizedTipPosition().y))); // 5
      //    debugDisplayString.append("\n");
      //       debugDisplayString.append(QString::number(debug_extendedFingerCounter));

      //works
      // if(direction.pitch() * RAD_TO_DEG > 30)
      // MouseKeyboardEmulation::MouseWheelUp((direction.pitch() * RAD_TO_DEG)/10);
      // if(direction.pitch() * RAD_TO_DEG < 30)
      // MouseKeyboardEmulation::MouseWheelDown(5);

    }
    else
    {

      if (fFistPositionY != 0)
        fFistPositionY = 0;
    }
    // std::cout << std::string(2, ' ') <<  "pitch: " << direction.pitch() * RAD_TO_DEG << " degrees, "
    //           << "roll: " << normal.roll() * RAD_TO_DEG << " degrees, "
    //           << "yaw: " << direction.yaw() * RAD_TO_DEG << " degrees" << std::endl;

    // Get the Arm bone
    Arm arm = hand.arm();
    // std::cout << std::string(2, ' ') <<  "Arm direction: " << arm.direction()
    //           << " wrist position: " << arm.wristPosition()
    //           << " elbow position: " << arm.elbowPosition() << std::endl;

    // Get fingers
    fingers = hand.fingers();
    FingerLogic(hand.isLeft() ? handLeft : handRight);

  }

}
Пример #6
0
 static void constructorTest(){
   Hand h = Hand();
   assert(h.getSize() == 0);
 }
Пример #7
0
int wam_main(int argc, char** argv, ProductManager& pm,
		systems::Wam<DOF>& wam) {
	BARRETT_UNITS_TEMPLATE_TYPEDEFS(DOF);

	typedef Hand::jp_type hjp_t;

	typedef boost::tuple<double, hjp_t> tuple_type;
	typedef systems::TupleGrouper<double, hjp_t> tg_type;
	tg_type tg;
	char tmpFile[] = "btXXXXXX";
	if (mkstemp(tmpFile) == -1) {
		printf("ERROR: Couldn't create temporary file!\n");
		return 1;
	}
	const double TRANSITION_DURATION = 0.5;

	wam.gravityCompensate();

//	printf("Press [Enter] to  go to given position");
//	waitForEnter();
//	jp_type startpos(0.0); // TODO : change here
//	wam.moveTo(startpos);

// Is an FTS attached?
	ForceTorqueSensor* fts = NULL;
	if (pm.foundForceTorqueSensor()) {
		fts = pm.getForceTorqueSensor();
		fts->tare();
	}

	// Is a Hand attached?
	Hand* hand = NULL;
	std::vector<TactilePuck*> tps;
	if (pm.foundHand()) {
		hand = pm.getHand();

		printf(
				">>> Press [Enter] to initialize Hand. (Make sure it has room!)");
		waitForEnter();
		hand->initialize();
		hand->trapezoidalMove(Hand::jp_type((1.0 / 3.0) * M_PI), Hand::SPREAD);
		hand->trapezoidalMove(Hand::jp_type((1.0 / 3.0) * M_PI), Hand::GRASP);
		hand->trapezoidalMove(Hand::jp_type((0.0) * M_PI), Hand::GRASP);

	}
	printf("Error 1 \n");
	tps = hand->getTactilePucks();
	// TODO write some error statement
	bool Release_Mode = 0;
	double delta_step = 0.002; //pm.getExecutionManager()->getPeriod();
	std::string input_angle_string;
	input_angle_string = argv[1];

	double input_angle = atoi(input_angle_string.c_str());
	double spread_angle = (input_angle / 180.0) * M_PI;
//	std::string threshold_impulse_str;
//	std::cout << "Enter the inpulse threshold limit: ";
//	std::cin >> threshold_impulse_str;
//	std::cout << "\n" << std::endl;
	std::string threshold_impulse_string;
	threshold_impulse_string = argv[2];

	double threshold_impulse = atof(threshold_impulse_string.c_str());

	printf("Press [Enter] to turn on the system");
	waitForEnter();
	printf("Error 2 \n");

	systems::Ramp time(pm.getExecutionManager(), 1.0);
//	const size_t PERIOD_MULTIPLIER = 1;
	const size_t PERIOD_MULTIPLIER = 1;
	systems::PeriodicDataLogger<tuple_type> logger(pm.getExecutionManager(),
			new log::RealTimeWriter<tuple_type>(tmpFile,
					PERIOD_MULTIPLIER * pm.getExecutionManager()->getPeriod()),
			PERIOD_MULTIPLIER);
	printf("Error 3 \n");

//	Hand_forcetorque_sense<DOF> hand_ft(hand, fts);
	Hand_tactile_sense hand_tact(hand, tps);
	main_processor<DOF> brain(hand, delta_step, spread_angle, threshold_impulse,
			Release_Mode);
	Hand_full_move hand_move(hand);

	systems::connect(tg.output, logger.input);
	systems::connect(time.output, brain.Current_time);
//	systems::connect(hand_ft.Force_hand, brain.Force_hand);
//	systems::connect(hand_ft.Torque_hand, brain.Torque_hand);
//	systems::connect(hand_ft.Acceleration_hand, brain.Acceleration_hand);
	systems::connect(hand_tact.Finger_Tactile_1, brain.Finger_Tactile_1);
	systems::connect(hand_tact.Finger_Tactile_2, brain.Finger_Tactile_2);
	systems::connect(hand_tact.Finger_Tactile_3, brain.Finger_Tactile_3);
	systems::connect(hand_tact.Finger_Tactile_4, brain.Finger_Tactile_4);
	systems::connect(brain.Desired_Finger_Angles, hand_move.Finger_Angles);

	systems::connect(time.output, tg.template getInput<0>());
	systems::connect(brain.Desired_Finger_Angles, tg.template getInput<1>());
//	systems::connect(hand_ft.Force_hand_cf, tg.template getInput<1>());


	printf("Error 4 \n");

	time.smoothStart(TRANSITION_DURATION);
	printf("Press [Enter] to stop.");
	waitForEnter();

	printf("Error 5 \n");
	logger.closeLog();
	time.smoothStop(TRANSITION_DURATION);
	wam.idle();
	printf("Error 6 \n");
	pm.getSafetyModule()->waitForMode(SafetyModule::IDLE);
	log::Reader<boost::tuple<tuple_type> > lr(tmpFile);
	lr.exportCSV(argv[3]);
	printf("Error 7 \n");
	printf("Output written to %s.\n", argv[3]);
	std::remove(tmpFile);
	return 0;

}
Пример #8
0
int poker_type(const Hand & h)
{
	int handSize = h.size();
	const int quad = 4;			//number of cards in a four of a kind
	const int triplet = 3;		//number of cards in a three of a kind
	const int pair = 2;			//number of cards in a two of a kind
	if (handSize == 5)
	{
		//checks the overall hand for a flush or a straight
		bool flush = h.cards[0].cardSuit == h.cards[1].cardSuit && h.cards[0].cardSuit == h.cards[2].cardSuit && h.cards[0].cardSuit == h.cards[3].cardSuit && h.cards[0].cardSuit == h.cards[4].cardSuit;
		bool straight = (h.cards[0].cardRank + 1) == h.cards[1].cardRank && (h.cards[1].cardRank + 1) == h.cards[2].cardRank && (h.cards[2].cardRank + 1) == h.cards[3].cardRank && (h.cards[3].cardRank + 1) == h.cards[4].cardRank;

		//checks for any multiples of a rank
		int maxCount = 0;		//maximum number of cards of the same rank in hand
		int secondCount = 0;	//second best amount of cards of the same rank (for full house and two pairs)
		int j;
		for (j = 0; j < handSize; j++)		//go through all cards in hand beginning with first one
		{

			Card cardOne = h.cards[j];		//store card currently examined
			int crntCount = 1;				//there are one of that rank so far

			int k;
			for (k = j + 1; k < handSize; ++k)	//go through rest of cards finding the rest of that rank
			{

				Card cardTwo = h.cards[k];

				if (cardOne.cardRank == cardTwo.cardRank)	//check if ranks are the same
				{

					++j;		//increment j so we dont double count the matching card
					++crntCount;	//increment count of the rank seen

				}
				else		//since cards are sorted, we know we will not hit any more of that rank once we find the first that is not of that rank so we can break
				{

					break;

				}
			}

			if (crntCount > maxCount)		//if we found a new maximum set it as so
			{

				secondCount = maxCount;
				maxCount = crntCount;

			}
			else if (crntCount > secondCount)		//if we found a new second most cards set it as so
			{

				secondCount = crntCount;

			}
		}

		//go through all hand possibilities starting with the best down to the worst and declare which we match
		if (flush && straight)
		{

			return poker_ranks::straightFlush;

		}
		else if (maxCount == quad)
		{

			return poker_ranks::fourOfAKind;

		}
		else if (maxCount == triplet && secondCount == pair)
		{

			return poker_ranks::fullHouse;

		}
		else if (flush)
		{

			return poker_ranks::flush;

		}
		else if (straight)
		{

			return poker_ranks::striaght;

		}
		else if (maxCount == triplet)
		{

			return poker_ranks::threeOfAKind;

		}
		else if (maxCount == pair && secondCount == pair)
		{

			return poker_ranks::twoPairs;

		}
		else if (maxCount == pair)
		{

			return poker_ranks::onePair;

		}
		else
		{

			return poker_ranks::noRank;

		}
	}
	return poker_ranks::INVALID;
}
Пример #9
0
Bet ComputerPlayer::calculateBet(SmallDeck comm, int minBet, GameState state) {

	srand((unsigned) time(0));
	ifstream inputFile;
	inputFile.open("PocketRanking.txt");
	char temp[4];
	int rank;
	int card1;
	int card2;
	int suited;
	int cardsuits;
	int ComputerRank;

	Card temp1;
	Card temp2;
	Card temp3;
	Hand Current;
	SmallDeck d = *pocket;

	if (!comm.isEmpty()) {
		Current.evaluate(d, comm);
	}
	temp1 | d.getCard(0);
	temp2 | d.getCard(1);

	if (temp1.getSuit() == temp2.getSuit()) {
		cardsuits = 1;
	} else {
		cardsuits = 0;
	}
	if (temp2.getValue() > temp1.getValue()) {
		temp3 | temp1;
		temp1 | temp2;
		temp2 | temp3;
	}

	for (int i = 0; i < 169; i++) {

		inputFile.getline(temp, 4, '	');
		inputFile >> temp;
		rank = atoi(temp);

		inputFile.getline(temp, 4, '	');
		inputFile >> temp;
		card1 = atoi(temp);

		inputFile.getline(temp, 4, '	');
		inputFile >> temp;
		card2 = atoi(temp);

		inputFile.getline(temp, 4, '	');
		inputFile >> temp;
		suited = atoi(temp);

		if (card1 == temp1.getValue() && card2 == temp2.getValue()
				&& suited == cardsuits)
			ComputerRank = rank;

	}

	int PC; //PocketConfidence
	int FP; //Flop Confidence
	if (ComputerRank <= 169 && ComputerRank >= 120)
		PC = 0;
	else if (ComputerRank <= 119 && ComputerRank >= 80)
		PC = 1;
	else if (ComputerRank <= 79 && ComputerRank >= 30)
		PC = 2;
	else if (ComputerRank <= 29 && ComputerRank >= 20)
		PC = 3;
	else if (ComputerRank <= 19 && ComputerRank >= 10)
		PC = 4;
	else if (ComputerRank <= 9 && ComputerRank >= 1)
		PC = 5;

	BetAction betAct = CALL;
	int betAmt = 0;
	int percent = rand() % 10;
	if (state == NEWROUND) {

		switch (PC) {
		case 0: {
			if (percent < 5) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else {
				betAct = CALL;
				betAmt = minBet;
			}
			break;
		}
		case 1: {
			if (percent < 3) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet; //	betAmt = money < betAmt ? money : betAmt;

			}
			break;
		}
		case 2: {
			if (percent < 1) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else if (percent < 8) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 3: {
			if (percent < 8) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 4: {

			if (percent < 7) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 5: {
			if (percent < 5) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}

		}
	} else {
		if (Current.getType() < 13 && Current.getType() >= 0 && PC > 2)
			FP = PC;
		else if (Current.getType() < 13 && Current.getType() >= 0 && PC <= 2)
			FP = PC - 1;
		else if (Current.getType() < 26 && Current.getType() >= 13 && PC > 2)
			FP = PC + 2;
		else if (Current.getType() < 26 && Current.getType() >= 13 && PC <= 2)
			FP = PC + 1;
		else if (Current.getType() < 38 && Current.getType() >= 26 && PC == 1)
			FP = PC + 3;
		else if (Current.getType() < 38 && Current.getType() >= 26 && PC > 1)
			FP = PC + 4;
		else if (Current.getType() < 106 && Current.getType() >= 38)
			FP = 10;
		switch (FP) {
		case -1: {
			if (minBet == 0) {
				betAct = CALL;
				betAmt = 0;
			} else {
				betAct = FOLD;
				betAmt = 0;
			}
			break;
		}
		case 0: {
			if (percent < 9) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}

			} else {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			}
			break;
		}
		case 1: {
			if (percent < 8) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			}
			break;
		}
		case 2: {
			if (percent < 7) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			}
			break;
		}
		case 3: {
			if (percent < 5) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else if (percent < 9) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 4: {
			if (percent < 3) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else if (percent < 8) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 5: {
			if (percent < 1) {
				if (minBet == 0) {
					betAct = CALL;
					betAmt = 0;
				} else {
					betAct = FOLD;
					betAmt = 0;
				}
				break;
			} else if (percent < 8) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 6: {
			if (percent < 8) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 7: {
			if (percent < 8) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 8: {
			if (percent < 7) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			}
			break;
		}
		case 9: {
			if (percent < 7) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else if (percent < 9) {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 120 : 3 * minBet;
			}
			break;
		}
		case 10: {
			if (percent < 3) {
				betAct = CALL;
				betAmt = minBet == 0 ? 40 : minBet;
			} else if (percent < 8) {
				betAct = RAISE;
				betAmt = minBet == 0 ? 80 : 2 * minBet;
			} else {
				betAct = RAISE;
				betAmt = minBet == 0 ? 120 : 3 * minBet;
			}
			break;
		}

		}
	}
	betAmt = money < betAmt ? money : betAmt;
	return Bet(betAct, betAmt);
}
Пример #10
0
void LeapHander::frame(pugi::xml_node &frameNode){
	Leap::Frame currentFrame = m_sampleListener.frame();
	m_lock.lock();
	frameNode.append_attribute("id").set_value(currentFrame.id());
	pugi::xml_node handList = frameNode.append_child("hands");
	HandList hands = currentFrame.hands();
	
	for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
		// Get the first hand
		const Hand hand = *hl;
		pugi::xml_node handNode = handList.append_child("hand");
		handNode.append_attribute("id").set_value(hand.id());
		std::string handType;
		if (hand.isLeft()) {
			handType = "Left";
		}
		else {
			handType = "Right";
		}
		handNode.append_attribute("type").set_value(handType.c_str());
		
		pugi::xml_node positionNode = handNode.append_child("position");
		positionToXml(positionNode, hand.palmPosition());
		
		/*pugi::xml_node normalNode = handNode.append_child("normal");
		positionToXml(normalNode, hand.palmNormal());

		pugi::xml_node directionNode = handNode.append_child("direction");
		positionToXml(directionNode, hand.direction());

		pugi::xml_node rotationNode = handNode.append_child("basis");
		rotationToXml(rotationNode, hand.basis());*/
		//// Get fingers
		pugi::xml_node fingerList = handNode.append_child("fingers");
		const FingerList fingers = hand.fingers();
		for (FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) {
			const Finger finger = *fl;
			pugi::xml_node fingerNode = fingerList.append_child("finger");
			fingerNode.append_attribute("id").set_value(finger.id());
			fingerNode.append_attribute("name").set_value(fingerNames[finger.type()].c_str());
			pugi::xml_node boneList = fingerNode.append_child("bones");
			

			// Get finger bones
			for (int b = 0; b < 4; ++b) {
				Bone::Type boneType = static_cast<Bone::Type>(b);
				Bone bone = finger.bone(boneType);
				pugi::xml_node boneNode = boneList.append_child("bone");
				boneNode.append_attribute("length").set_value(bone.length());
				boneNode.append_attribute("name").set_value(boneNames[boneType].c_str());

				pugi::xml_node prevJoint = boneNode.append_child("prevJoint");
				positionToXml(prevJoint, bone.prevJoint());

				pugi::xml_node nextJoint = boneNode.append_child("nextJoint");
				positionToXml(nextJoint, bone.nextJoint());

				/*pugi::xml_node rotation = boneNode.append_child("basis");
				rotationToXml(rotation, bone.basis());*/
			}
		}
	}
	m_lock.unlock();
}
Пример #11
0
void AirwritingListener::onFrame(const Controller& controller) {
    // Get the most recent frame and report some basic information
    const Frame frame = controller.frame();
    unsigned long long timestamp = frame.timestamp();
    
    /*
    std::cout << "Frame id: " << frame.id()
    << ", timestamp: " << frame.timestamp()
    << ", hands: " << frame.hands().count()
    << ", extended fingers: " << frame.fingers().extended().count()
    << ", tools: " << frame.tools().count()
    << ", gestures: " << frame.gestures().count() << std::endl;
    */

    
    HandList hands = frame.hands();
    for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
        // Get the first hand
        const Hand hand = *hl;
        std::string handType = hand.isLeft() ? "Left hand" : "Right hand";
        
        /*
        std::cout << std::string(2, ' ') << handType << ", id: " << hand.id()
        << ", palm position: " << hand.palmPosition() << std::endl;
        */
        
        /*
        // Get the hand's normal vector and direction
        const Vector normal = hand.palmNormal();
        const Vector direction = hand.direction();
        */
        
        /*
        // Calculate the hand's pitch, roll, and yaw angles
        std::cout << std::string(2, ' ') <<  "pitch: " << direction.pitch() * RAD_TO_DEG << " degrees, "
        << "roll: " << normal.roll() * RAD_TO_DEG << " degrees, "
        << "yaw: " << direction.yaw() * RAD_TO_DEG << " degrees" << std::endl;
        */
        
        /*
        // Get the Arm bone
        Arm arm = hand.arm();
        std::cout << std::string(2, ' ') <<  "Arm direction: " << arm.direction()
        << " wrist position: " << arm.wristPosition()
        << " elbow position: " << arm.elbowPosition() << std::endl;
        */
        
        // Get fingers
        const FingerList fingers = hand.fingers();
        for (FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) {
            const Finger finger = *fl;
            sample(finger, timestamp);
            
            /*
            std::cout << std::string(4, ' ') <<  fingerNames[finger.type()]
            << " finger, id: " << finger.id()
            << ", length: " << finger.length()
            << "mm, width: " << finger.width() << std::endl;
            */
            
            /*
            // Get finger bones
            for (int b = 0; b < 4; ++b) {
                Bone::Type boneType = static_cast<Bone::Type>(b);
                Bone bone = finger.bone(boneType);
                std::cout << std::string(6, ' ') <<  boneNames[boneType]
                << " bone, start: " << bone.prevJoint()
                << ", end: " << bone.nextJoint()
                << ", direction: " << bone.direction() << std::endl;
            }
            */
        }
    }
    
    
    /*
    // Get tools
    const ToolList tools = frame.tools();
    for (ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) {
        const Tool tool = *tl;
        std::cout << std::string(2, ' ') <<  "Tool, id: " << tool.id()
        << ", position: " << tool.tipPosition()
        << ", direction: " << tool.direction() << std::endl;
    }
    */
    

    // Get gestures
    const GestureList gestures = frame.gestures();
    for (int g = 0; g < gestures.count(); ++g) {
        Gesture gesture = gestures[g];
        
        switch (gesture.type()) {
            case Gesture::TYPE_CIRCLE:
            {
                CircleGesture circle = gesture;
                std::string clockwiseness;
                
                if (circle.pointable().direction().angleTo(circle.normal()) <= PI/2) {
                    clockwiseness = "clockwise";
                } else {
                    clockwiseness = "counterclockwise";
                }
                
                // Calculate angle swept since last frame
                float sweptAngle = 0;
                if (circle.state() != Gesture::STATE_START) {
                    CircleGesture previousUpdate = CircleGesture(controller.frame(1).gesture(circle.id()));
                    sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;
                }
                /*
                std::cout << std::string(2, ' ')
                << "Circle id: " << gesture.id()
                << ", state: " << stateNames[gesture.state()]
                << ", progress: " << circle.progress()
                << ", radius: " << circle.radius()
                << ", angle " << sweptAngle * RAD_TO_DEG
                <<  ", " << clockwiseness << std::endl;
                */
                break;
            }
            case Gesture::TYPE_SWIPE:
            {
                SwipeGesture swipe = gesture;
                /*
                std::cout << std::string(2, ' ')
                << "Swipe id: " << gesture.id()
                << ", state: " << stateNames[gesture.state()]
                << ", direction: " << swipe.direction()
                << ", speed: " << swipe.speed() << std::endl;
                */
                break;
            }
            case Gesture::TYPE_KEY_TAP:
            {
                KeyTapGesture tap = gesture;
                push(timestamp);
                /*
                std::cout << std::string(2, ' ')
                << "Key Tap id: " << gesture.id()
                << ", state: " << stateNames[gesture.state()]
                << ", position: " << tap.position()
                << ", direction: " << tap.direction()<< std::endl;
                */
                break;
            }
            case Gesture::TYPE_SCREEN_TAP:
            {
                ScreenTapGesture screentap = gesture;
                /*
                std::cout << std::string(2, ' ')
                << "Screen Tap id: " << gesture.id()
                << ", state: " << stateNames[gesture.state()]
                << ", position: " << screentap.position()
                << ", direction: " << screentap.direction()<< std::endl;
                */
                break;
            }
            default:
                /*
                std::cout << std::string(2, ' ')  << "Unknown gesture type." << std::endl;
                */
                break;
        }
    }

    
    /*
    if (!frame.hands().isEmpty() || !gestures.isEmpty()) {
        std::cout << std::endl;
    }
    */
    
}
void LeapController::update() {   
    hands = leap.getLeapHands();
    
    if(leap.isFrameNew() && hands.size()){
        
        for(int i = 0; i < hands.size(); i++){
            
            Hand hand = hands[i];
            
            if (handsPrevious.size() == hands.size() && hand.fingers().count() == 3){
                
                float dx =  hand.palmPosition().x - handsPrevious[i].palmPosition().x;
                float dy =  hand.palmPosition().z - handsPrevious[i].palmPosition().z;
                float dz = -hand.palmPosition().y + handsPrevious[i].palmPosition().y;
                int numFingers = hands[i].fingers().count();
                
//                horizontalPan = (numFingers == 2);
                horizontalPan = false;
                verticalPan = true;
                
                pan(dx,dy,dz);
            }
        }
    }
    
    Frame frame = controller.frame();
    GestureList gestures =  framePrevious.isValid()       ?
    frame.gestures(framePrevious) :
    frame.gestures();
    framePrevious = frame;
    
    for (size_t i=0; i < gestures.count(); i++) {
        if (gestures[i].type() == Gesture::TYPE_SCREEN_TAP) {
            ScreenTapGesture tap = gestures[i];
            static GestureEventArgs args;
            args.pos = ofVec3f(tap.position().x, tap.position().y, tap.position().z);
            ofNotifyEvent(onTapScreen, args, this);
        } else if (gestures[i].type() == Gesture::TYPE_KEY_TAP) {
            KeyTapGesture tap = gestures[i];
            static GestureEventArgs args;
            args.pos = ofVec3f(tap.position().x, tap.position().y, tap.position().z);
            ofNotifyEvent(onTapDown, args, this);
            
            //cout << "LEAP TAP GESTURE AT: " << pos << endl;
        
        } else if (gestures[i].type() == Gesture::TYPE_SWIPE) {
            SwipeGesture swipe = gestures[i];
            Vector diff = 0.004f*(swipe.position() - swipe.startPosition());
            static GestureEventArgs args;
            args.pos = ofVec3f(swipe.position().x, swipe.position().y, swipe.position().z);
            args.startPos = ofVec3f(swipe.startPosition().x, swipe.startPosition().y, swipe.startPosition().z);
            args.state = swipe.state();
            ofNotifyEvent(onSwipe, args, this);
            
            //cout << "LEAP SWIPE GESTURE" << endl;
        
        } else if (gestures[i].type() == Gesture::TYPE_CIRCLE) {
            CircleGesture circle = gestures[i];
            float progress = circle.progress();
            
            if (progress >= 1.0f) {
                double curAngle = 6.5;
                
                //cout << "LEAP CIRCLE GESTURE" << endl;
            }
            static GestureEventArgs args;
            args.pos = ofVec3f(circle.center().x, circle.center().y, circle.center().z);
            args.normal = ofVec3f(circle.normal().x, circle.normal().y, circle.normal().z);
            args.progress = circle.progress();
            ofNotifyEvent(onCircle, args, this);
        }
    }
    
    handsPrevious = hands;
    
	leap.markFrameAsOld();
    
    SceneController::update();
}
Пример #13
0
void LeapBrowser::drawHands()
{
	Frame frame = leap_controller.frame();

	math::vector trans = leap_transform.translation;
	math::quater rot_quat = leap_transform.rotation;
	math::vector rot_vect = math::ln( rot_quat );
	
	double angle = rot_vect.length() * 2.0;
	math::vector axis = ( angle != 0 ? rot_vect / angle : rot_vect );

	glMatrixMode( GL_MODELVIEW );
	glPushMatrix();
	glTranslatef( trans.x(), trans.y(), trans.z() );
	if( angle != 0 )
	{
		glRotatef( angle * 180.0 / M_PI, axis.x(), axis.y(), axis.z() );
	}

	HandList hands = frame.hands();
	for( HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl )
	{
		const Hand hand = *hl;

		float joint_radius = 5.0f;
		float bone_radius = 4.5f;

		Vector prev_palm_start(0,0,0);
		Vector prev_palm_end(0,0,0);

		int f = 0;
		const FingerList fingers = hand.fingers();
		for( FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl, ++f )
		{
			const Finger finger = *fl;

			Vector curr_palm_start(0,0,0);
			Vector curr_palm_end(0,0,0);

			for( int b=0; b < 4; b++ )
			{
				Bone::Type bone_type = static_cast<Bone::Type>( b );
				Bone bone = finger.bone( bone_type );

				Vector start = bone.prevJoint();
				Vector end = bone.nextJoint();

				math::position p0( start.x, start.y, start.z );
				math::position p1( end.x, end.y, end.z );

				if( is_tracking_pose == true && finger.type() == Finger::Type::TYPE_INDEX && b==3 )
				{
					drawing_tool.setColor( 1, 0, 0, 1 );
				}
				else
				{
					drawing_tool.setColor( 0.5, 0.7, 0.5, 1 );
				}
				drawing_tool.drawSphere( p1, joint_radius );
				
				drawing_tool.setColor( 0.5, 0.7, 0.5, 1 );
				drawing_tool.drawSphere( p0, joint_radius );
				drawing_tool.drawCylinder( p0, p1, bone_radius );

				//
				if( b == 0 && fl != fingers.begin() || b == 1 && fl == fingers.begin() )
				{
					curr_palm_start = start;
					curr_palm_end = end;
				}
			}

			if( f > 1 )	//fl != fingers.begin() )
			{
				drawing_tool.setColor( 0.5, 0.7, 0.5, 1 );
				drawing_tool.applyColor();

				glBegin( GL_QUADS );
				glVertex3f( prev_palm_start.x, prev_palm_start.y, prev_palm_start.z );
				glVertex3f( prev_palm_end.x, prev_palm_end.y, prev_palm_end.z );
				glVertex3f( curr_palm_end.x, curr_palm_end.y, curr_palm_end.z );
				glVertex3f( curr_palm_start.x, curr_palm_start.y, curr_palm_start.z );
				glEnd();
			}

			prev_palm_start = curr_palm_start;
			prev_palm_end = curr_palm_end;
		}
	}

	glPopMatrix();
}
Пример #14
0
void Game::AI()
{
	//AI works by:
	//1. using a killing move (if any)
	//2. giving the largest number of digits/points to opponent
	Hand *usePtr = m_gameWorld->tLeft();
	Hand *tarPtr = m_gameWorld->bLeft();
	int largestSum = 0;
	if (m_gameWorld->OFOn())
	{
		int sum = 0;
		if (!usePtr->isDead())
		{
			if (!tarPtr->isDead())
			{
				largestSum = m_gameWorld->tLeft()->numDigits() + m_gameWorld->bLeft()->numDigits() % 5;
				if (largestSum == 0) 
				{
					m_gameWorld->attack(usePtr,tarPtr); return;
				}
			}
			if (!m_gameWorld->bRight()->isDead())
			{
				sum = m_gameWorld->tLeft()->numDigits() + m_gameWorld->bRight()->numDigits() % 5;
				if (sum == 0) 
				{
					m_gameWorld->attack(usePtr,m_gameWorld->bRight()); return;
				}
				if (sum > largestSum)
				{
					largestSum = sum;
					tarPtr = m_gameWorld->bRight();
				}
			}
		}
		if (!m_gameWorld->tRight()->isDead())
		{
			if (!m_gameWorld->bLeft()->isDead())
			{
				sum = m_gameWorld->tRight()->numDigits() + m_gameWorld->bLeft()->numDigits() % 5;
				if (sum == 0) 
				{
					m_gameWorld->attack(m_gameWorld->tRight(),m_gameWorld->bLeft()); return;
				}
				if (sum > largestSum)
				{
					largestSum = sum; 
					usePtr = m_gameWorld->tRight();
					tarPtr = m_gameWorld->bLeft();
				}
			}
			if (!m_gameWorld->bRight()->isDead())
			{
				sum = m_gameWorld->tRight()->numDigits() + m_gameWorld->bRight()->numDigits() % 5;
				if (sum == 0) 
				{
					m_gameWorld->attack(m_gameWorld->tRight(),m_gameWorld->bRight()); return;
				}
				if (sum > largestSum)
				{
					largestSum = sum;
					usePtr = m_gameWorld->tRight();
					tarPtr = m_gameWorld->bRight();
				}
			}
		}
	}
	else
	{
		int sum = 0;
		if (!usePtr->isDead())
		{
			if (!tarPtr->isDead())
				largestSum = m_gameWorld->tLeft()->numDigits() + m_gameWorld->bLeft()->numDigits();
			if (!m_gameWorld->bRight()->isDead())
			{
				sum = m_gameWorld->tLeft()->numDigits() + m_gameWorld->bRight()->numDigits();
				if (sum > largestSum)
				{
					largestSum = sum;
					tarPtr = m_gameWorld->bRight();
				}
			}
		}
		if (!m_gameWorld->tRight()->isDead())
		{
			if (!m_gameWorld->bLeft()->isDead())
			{
				sum = m_gameWorld->tRight()->numDigits() + m_gameWorld->bLeft()->numDigits();
				if (sum > largestSum)
				{
					largestSum = sum; 
					usePtr = m_gameWorld->tRight();
					tarPtr = m_gameWorld->bLeft();
				}
			}
			if (!m_gameWorld->bRight()->isDead())
			{
				sum = m_gameWorld->tRight()->numDigits() + m_gameWorld->bRight()->numDigits();
				if (sum > largestSum)
				{
					largestSum = sum;
					usePtr = m_gameWorld->tRight();
					tarPtr = m_gameWorld->bRight();
				}
			}
		}
	}
	m_gameWorld->attack(usePtr,tarPtr);
	cout << "AI has decided. Press 'enter' to continue.\n";
	cin.ignore(1000,'\n');
}
Пример #15
0
void SixenseManager::update(float deltaTime) {
#ifdef HAVE_SIXENSE
    Hand* hand = DependencyManager::get<AvatarManager>()->getMyAvatar()->getHand();
    if (_isInitialized && _isEnabled) {
#ifdef __APPLE__
        SixenseBaseFunction sixenseGetNumActiveControllers =
        (SixenseBaseFunction) _sixenseLibrary->resolve("sixenseGetNumActiveControllers");
#endif
        
        if (sixenseGetNumActiveControllers() == 0) {
            _hydrasConnected = false;
            return;
        }
        
        PerformanceTimer perfTimer("sixense");
        if (!_hydrasConnected) {
            _hydrasConnected = true;
            UserActivityLogger::getInstance().connectedDevice("spatial_controller", "hydra");
        }
        
#ifdef __APPLE__
        SixenseBaseFunction sixenseGetMaxControllers =
        (SixenseBaseFunction) _sixenseLibrary->resolve("sixenseGetMaxControllers");
#endif
        
        int maxControllers = sixenseGetMaxControllers();
        
        // we only support two controllers
        sixenseControllerData controllers[2];
        
#ifdef __APPLE__
        SixenseTakeIntFunction sixenseIsControllerEnabled =
        (SixenseTakeIntFunction) _sixenseLibrary->resolve("sixenseIsControllerEnabled");
        
        SixenseTakeIntAndSixenseControllerData sixenseGetNewestData =
        (SixenseTakeIntAndSixenseControllerData) _sixenseLibrary->resolve("sixenseGetNewestData");
#endif
        int numControllersAtBase = 0;
        int numActiveControllers = 0;
        for (int i = 0; i < maxControllers && numActiveControllers < 2; i++) {
            if (!sixenseIsControllerEnabled(i)) {
                continue;
            }
            sixenseControllerData* data = controllers + numActiveControllers;
            ++numActiveControllers;
            sixenseGetNewestData(i, data);
            
            //  Set palm position and normal based on Hydra position/orientation
            
            // Either find a palm matching the sixense controller, or make a new one
            PalmData* palm;
            bool foundHand = false;
            for (size_t j = 0; j < hand->getNumPalms(); j++) {
                if (hand->getPalms()[j].getSixenseID() == data->controller_index) {
                    palm = &(hand->getPalms()[j]);
                    foundHand = true;
                }
            }
            if (!foundHand) {
                PalmData newPalm(hand);
                hand->getPalms().push_back(newPalm);
                palm = &(hand->getPalms()[hand->getNumPalms() - 1]);
                palm->setSixenseID(data->controller_index);
                qCDebug(interfaceapp, "Found new Sixense controller, ID %i", data->controller_index);
            }
            
            // Disable the hands (and return to default pose) if both controllers are at base station
            if (foundHand) {
                palm->setActive(!_controllersAtBase);
            } else {
                palm->setActive(false); // if this isn't a Sixsense ID palm, always make it inactive
            }
            
            
            //  Read controller buttons and joystick into the hand
            palm->setControllerButtons(data->buttons);
            palm->setTrigger(data->trigger);
            palm->setJoystick(data->joystick_x, data->joystick_y);
            
            // Emulate the mouse so we can use scripts
            if (Menu::getInstance()->isOptionChecked(MenuOption::SixenseMouseInput) && !_controllersAtBase) {
                emulateMouse(palm, numActiveControllers - 1);
            }
            
            // NOTE: Sixense API returns pos data in millimeters but we IMMEDIATELY convert to meters.
            glm::vec3 position(data->pos[0], data->pos[1], data->pos[2]);
            position *= METERS_PER_MILLIMETER;
            
            // Check to see if this hand/controller is on the base
            const float CONTROLLER_AT_BASE_DISTANCE = 0.075f;
            if (glm::length(position) < CONTROLLER_AT_BASE_DISTANCE) {
                numControllersAtBase++;
            }
            
            // Transform the measured position into body frame.
            glm::vec3 neck = _neckBase;
            // Zeroing y component of the "neck" effectively raises the measured position a little bit.
            neck.y = 0.0f;
            position = _orbRotation * (position - neck);
            
            //  Rotation of Palm
            glm::quat rotation(data->rot_quat[3], -data->rot_quat[0], data->rot_quat[1], -data->rot_quat[2]);
            rotation = glm::angleAxis(PI, glm::vec3(0.0f, 1.0f, 0.0f)) * _orbRotation * rotation;
            
            //  Compute current velocity from position change
            glm::vec3 rawVelocity;
            if (deltaTime > 0.0f) {
                rawVelocity = (position - palm->getRawPosition()) / deltaTime;
            } else {
                rawVelocity = glm::vec3(0.0f);
            }
            palm->setRawVelocity(rawVelocity);   //  meters/sec
            
            // adjustment for hydra controllers fit into hands
            float sign = (i == 0) ? -1.0f : 1.0f;
            rotation *= glm::angleAxis(sign * PI/4.0f, glm::vec3(0.0f, 0.0f, 1.0f));
            
            //  Angular Velocity of Palm
            glm::quat deltaRotation = rotation * glm::inverse(palm->getRawRotation());
            glm::vec3 angularVelocity(0.0f);
            float rotationAngle = glm::angle(deltaRotation);
            if ((rotationAngle > EPSILON) && (deltaTime > 0.0f)) {
                angularVelocity = glm::normalize(glm::axis(deltaRotation));
                angularVelocity *= (rotationAngle / deltaTime);
                palm->setRawAngularVelocity(angularVelocity);
            } else {
                palm->setRawAngularVelocity(glm::vec3(0.0f));
            }
            
            if (_lowVelocityFilter) {
                //  Use a velocity sensitive filter to damp small motions and preserve large ones with
                //  no latency.
                float velocityFilter = glm::clamp(1.0f - glm::length(rawVelocity), 0.0f, 1.0f);
                position = palm->getRawPosition() * velocityFilter + position * (1.0f - velocityFilter);
                rotation = safeMix(palm->getRawRotation(), rotation, 1.0f - velocityFilter);
                palm->setRawPosition(position);
                palm->setRawRotation(rotation);
            } else {
                palm->setRawPosition(position);
                palm->setRawRotation(rotation);
            }
            
            // Store the one fingertip in the palm structure so we can track velocity
            const float FINGER_LENGTH = 0.3f;   //  meters
            const glm::vec3 FINGER_VECTOR(0.0f, 0.0f, FINGER_LENGTH);
            const glm::vec3 newTipPosition = position + rotation * FINGER_VECTOR;
            glm::vec3 oldTipPosition = palm->getTipRawPosition();
            if (deltaTime > 0.0f) {
                palm->setTipVelocity((newTipPosition - oldTipPosition) / deltaTime);
            } else {
                palm->setTipVelocity(glm::vec3(0.0f));
            }
            palm->setTipPosition(newTipPosition);
        }
        
        if (numActiveControllers == 2) {
            updateCalibration(controllers);
        }
        _controllersAtBase = (numControllersAtBase == 2);
    }
#endif  // HAVE_SIXENSE
}
Пример #16
0
//check to poker hands to see if the first has a better rank than the second
bool poker_rank(const Hand & h1, const Hand & h2)
{

	//get the type of poker hands (represented by integers)
	int h1_type = poker_type(h1);
	int h2_type = poker_type(h2);
	const int handsize = 5;
	const int offset = 1;
	const int firstPosition = 0;

	//if both hands are of the same type (and they each have the proper number of cards), then find out which is the higher of that type
	if (h1_type == h2_type && h1.size() == handsize)
	{

		//straights and straight flushes are sorted only by the highest card in their hand
		if (h1_type == poker_ranks::straightFlush || h1_type == poker_ranks::striaght)
		{

			return h2.cards[handsize - offset].cardRank < h1.cards[handsize - offset].cardRank;

		}
		//full houses and four of a kinds are sorted by their more frequent card then their less frequent card
		else if (h1_type == poker_ranks::fullHouse || h1_type == poker_ranks::fourOfAKind)
		{

			//get the count of the rank of the first card in the hand
			int count1 = rank_count(&h1.cards[firstPosition], &h1.cards[handsize - offset] + offset, *h1.cards.begin());
			int count2 = rank_count(&h2.cards[firstPosition], &h2.cards[handsize - offset] + offset, *h2.cards.begin());
			
			const int triplet = 3;

			Card h1big;
			Card h2big;
			Card h1small;
			Card h2small;
			
			//set the more frequent and less frequent cards from hand 1
			if (count1 >= triplet)
			{

				h1big = *h1.cards.begin();
				h1small = *h1.cards.end();
			
			}
			else
			{

				h1big = *h1.cards.end();
				h1small = *h1.cards.begin();
			
			}
			
			//set the more frequent and less frequent cards from hand 2
			if (count2 >= triplet)
			{

				h2big = *h2.cards.begin();
				h2small = *h2.cards.end();
			
			}
			else
			{

				h2big = *h2.cards.end();
				h2small = *h2.cards.begin();

			}

			return h2big.cardRank < h1big.cardRank || (h2big.cardRank == h1big.cardRank && h2small.cardRank < h1small.cardRank);

		}
		//flush hands and unranked hands are sorted by the highest card down
		else if (h1_type == poker_ranks::flush || h1_type == poker_ranks::noRank)
		{
			
			//start iterators at the last card in either hand
			int it = handsize - offset;

			//check if we have reached the first card
			while (it >= firstPosition)
			{

				//if the second hand's card comes before the first hands card, the first hand is greater
				if (h2.cards[it].cardRank < h1.cards[it].cardRank)
				{

					return true;

				}
				//if the second hands card comes after the first hands card, the second hand is greater
				if (h2.cards[it].cardRank > h1.cards[it].cardRank)
				{

					return false;
				
				}

				--it;

			}

			//if both hands have the same ranked cards, then the first hand is not greater
			return false;
		
		}
		//three of a kind hands are sorted by the rank of their three of a kind card
		else if (h1_type == poker_ranks::threeOfAKind)
		{

			//with three cards of the same rank, one of the three will always be at the middle position of the hands since the hands are sorted and we have a maximum of 5 cards
			const int midVal = 2;
			return h2.cards[midVal].cardRank < h1.cards[midVal].cardRank;

		}
		//two pairs hands are sorted by their first pair, then their second pair, then their remaining cards
		else if (h1_type == poker_ranks::twoPairs)
		{

			//begin with the highest card in the hands
			int it1 = handsize - offset;
			int it2 = handsize - offset;

			Card h1one;
			bool seth1one = false;
			Card h2one;
			bool seth2one = false;
			Card h1bigpair;
			bool seth1bigpair = false;
			Card h2bigpair;
			bool seth2bigpair = false;
			Card h1smallpair;
			bool seth1smallpair = false;
			Card h2smallpair;
			bool seth2smallpair = false;

			//go through hands setting the two pairs and the additional card
			while (it1 >= firstPosition && it2 >= firstPosition)
			{

				const int onlyOne = 1;
				const int pair = 2;
				int count1;
				int count2;

				//if we are at the first card in the hand, the cound is one
				if (it1 == firstPosition)
				{

					count1 = onlyOne;
				
				}
				//otherise we check the local region to see if there is another one of this card
				else
				{

					count1 = rank_count(&h1.cards[it1] - offset, &h1.cards[it1] + offset, h1.cards[it1]);
				
				}
				//if we are at the first card in the hand, the cound is one
				if (it2 == firstPosition)
				{

					count2 = onlyOne;

				}
				//otherise we check the local region to see if there is another one of this card
				else
				{

					count2 = rank_count(&h2.cards[it2] - offset, &h2.cards[it2] + offset, h2.cards[it2]);
				
				}
				if (count1 == onlyOne)
				{

					//if we havent already set the one card, we set it
					if (!seth1one)
					{

						h1one = h1.cards[it1];
						seth1one = true;

					}

					--it1;

				}
				if (count2 == onlyOne)
				{

					//if we havent already set the one card, we set it
					if (!seth2one)
					{

						h2one = h2.cards[it2];
						seth2one = true;

					}

					--it2;
				
				}
				if (count1 == pair)
				{
					//first we attempt to set the larger pair, but if we have already set it we set the smaller pair (unless it is also already set)
					if (!seth1bigpair)
					{

						h1bigpair = h1.cards[it1];
						seth1bigpair = true;

					}
					else if (!seth1smallpair)
					{

						h1smallpair = h1.cards[it1];
						seth1smallpair = true;

					}

					//decrement twice since we already acounted for both cards in the pair
					--it1;
					--it1;

				}
				if (count2 == 2)
				{
					//first we attempt to set the larger pair, but if we have already set it we set the smaller pair (unless it is also already set)
					if (!seth2bigpair)
					{

						h2bigpair = h2.cards[it2];
						seth2bigpair = true;

					}
					else if (!seth2smallpair)
					{

						h2smallpair = h2.cards[it2];
						seth2smallpair = true;

					}

					//recrement twice since we already accounted for both cards in the pair
					--it2;
					--it2;

				}
			}

			return (h2bigpair.cardRank < h1bigpair.cardRank) || (h2bigpair.cardRank == h1bigpair.cardRank && h2smallpair.cardRank < h1smallpair.cardRank) || (h2bigpair.cardRank == h1bigpair.cardRank && h2smallpair.cardRank == h1smallpair.cardRank && h2one.cardRank < h1one.cardRank);
		
		}
		//finally, if we only have one pair, we sort by the piar then the remaining cards
		else
		{

			int it1 = handsize - offset;
			int it2 = handsize - offset;

			const int onlyOne = 1;
			const int pair = 2;

			Card h1pair;
			Card h2pair;

			while (it1 >= firstPosition && it2 >= firstPosition)
			{

				int count1;
				int count2;

				//if we are at the first card in the hand, the cound is one
				if (it1 == firstPosition)
				{

					count1 = onlyOne;

				}
				//otherise we check the local region to see if there is another one of this card
				else
				{

					count1 = rank_count(&h1.cards[it1] - offset, &h1.cards[it1] + offset, h1.cards[it1]);
				
				}

				//if we are at the first card in the hand, the cound is one
				if (it2 == firstPosition)
				{

					count2 = onlyOne;
				
				}
				//otherise we check the local region to see if there is another one of this card
				else
				{

					count2 = rank_count(&h2.cards[it2] - offset, &h2.cards[it2] + offset, h2.cards[it2]);
				
				}

				if (count1 == onlyOne)
				{

					//we dont have a pair yet so just pass it.
					--it1;

				}
				if (count2 == onlyOne)
				{

					//we dont have a pair yet so just pass it.
					--it2;
				}
				if (count1 == pair)
				{

					//we found the pair so set it as found
					h1pair = h1.cards[it1];
					//decrement twice since we found the piar
					--it1;
					--it1;

				}
				if (count2 == pair)
				{

					//we dond the pair sp set it as found
					h2pair = h2.cards[it2];
					//decrement twice since we found the pair
					--it2;
					--it2;

				}

			}
			//if the pairs are equal, check the remaining cards
			if (h1pair.cardRank == h2pair.cardRank)
			{
				it1 = handsize - offset;
				it2 = handsize - offset;
				while (it1 >= firstPosition && it2 >= firstPosition)
				{

					//if this card is a card in the pair just pass it
					if (h1.cards[it1].cardRank == h1pair.cardRank || h2.cards[it2].cardRank == h2pair.cardRank)
					{

						if (h1.cards[it1].cardRank == h1pair.cardRank)
						{

							--it1;

						}
						if (h2.cards[it2].cardRank == h2pair.cardRank)
						{

							--it2;

						}
					}
					//if this card isnt a card in the pair compare
					else
					{

						//if the second hands card is smaller, then this hand is greater
						if (h2.cards[it2].cardRank < h1.cards[it1].cardRank)
						{

							return true;

						}
						//if the second hands card is greater, then the second hand is greater
						if (h2.cards[it2].cardRank > h1.cards[it1].cardRank)
						{

							return false;

						}
						--it1;
						--it2;
					}
				}

				//if we go through all cards finding the same ranks, then we are not greater than the second hand
				return false;

			}
			//if the pairs are not equal return which one is larger
			else
			{

				return h2pair.cardRank < h1pair.cardRank;

			}
		}
	}
	//if they are different types, then return which is the higher type
	else
	{

		return h1_type > h2_type;

	}
}
Пример #17
0
void LeapInput::onFrame(const Controller& controller)
{
	Frame frame = controller.frame();
	HandList hands = frame.hands();
	this->hands = hands.count();
	if(hands.count() == 2)
	{
		Hand leftHand = hands.leftmost();
		Hand rightHand = hands.rightmost();
		leftHandY = leftHand.palmPosition().y;
		rightHandY = rightHand.palmPosition().y;
		leftFingers = leftHand.fingers().count();
		rightFingers = rightHand.fingers().count();

		float threshold = tanf(5* 3.141592f / 180.0f);
		float maxTan = tanf(45 * 3.141592f / 180.0f);
		if(leftHand.palmPosition().x != rightHand.palmPosition().x){
			float tanValue = fabs((leftHand.palmPosition().y - rightHand.palmPosition().y) / (leftHand.palmPosition().x - rightHand.palmPosition().x));
			if(tanValue > threshold){
				curve = tanValue  / maxTan;
				if(curve > 1)
					curve = 1;
			}else
				curve = 0;
		}else
			curve = 0;
	}
	else
	{
		leftHandY = rightHandY = 0;
	}

	boost = false;
	GestureList gestureList = frame.gestures();
	for(GestureList::const_iterator i = gestureList.begin(); i != gestureList.end(); ++i)
	{
		Gesture gesture = *i;
		if(gesture.state() != Gesture::State::STATE_INVALID)
		{
			switch(gesture.type())
			{
			case Gesture::Type::TYPE_SCREEN_TAP:
				boost = true;
				break;
			}
			
		}
	}

	back = false;
	if(hands.count() == 2 && leftFingers == 1 && rightFingers == 1 &&
		hands.leftmost().fingers()[0].direction().z > 0 &&
		hands.rightmost().fingers()[0].direction().z > 0)
	{
		back = true;
	}

	//accelGesture = brakeGesture = false;
	//GestureList gestureList = frame.gestures();
	//for(GestureList::const_iterator i = gestureList.begin(); i != gestureList.end(); ++i)
	//{
	//	Gesture gesture = *i;
	//	if(gesture.state() != Gesture::State::STATE_INVALID)
	//	{
	//		if(typeid(gesture) == typeid(MyGesture))
	//		{
	//			accelGesture = true;
	//		}
	//		
	//	}
	//}
}
Пример #18
0
int wam_main(int argc, char** argv, ProductManager& pm, systems::Wam<DOF>& wam) {

    BARRETT_UNITS_TEMPLATE_TYPEDEFS(DOF);

    // These vectors are fixed sized, stack allocated, and zero-initialized.
    jp_type jp;  // jp is a DOFx1 column vector of joint positions
    cp_type cp;  // cp is a 3x1 vector representing a Cartesian position

    wam.gravityCompensate();
    printMenu();
    Hand* hand = pm.getHand();


// Write a socket program here. It is a server socket that would close only when the program closes
// This client socket would connect to a server socket on a external machine a recieve data from it
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    int status;
    struct addrinfo host_info;
    struct addrinfo *host_info_list;
    memset(&host_info, 0, sizeof host_info);
    host_info.ai_family = AF_UNSPEC;
    host_info.ai_socktype = SOCK_STREAM;
    host_info.ai_flags = AI_PASSIVE;
    status = getaddrinfo("192.168.0.110", "5555", &host_info, &host_info_list); //192.168.0.110 this is the wam(server) address
    int socketfd ;
    socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol);
    int yes = 1;
    status = setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
    status = bind(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
    status =  listen(socketfd, 5);
    int new_sd;
    struct sockaddr_storage their_addr;
    socklen_t addr_size = sizeof(their_addr);
    new_sd = accept(socketfd, (struct sockaddr *)&their_addr, &addr_size);
    std::string line;

    bool going = true;


    while (going) {
        std::cout << "Whiel loop starts" << std::endl;
//-----------------------------------------------------------------------------------
        ssize_t bytes_recieved;
        char incomming_data_buffer[1000];
        bytes_recieved = recv(new_sd, incomming_data_buffer,1000, 0);
        std::cout << bytes_recieved << std::endl;
//    if (bytes_recieved == 0) std::cout << "host shut down." << std::endl ;
//    if (bytes_recieved == -1)std::cout << "recieve error!" << std::endl ;
        incomming_data_buffer[bytes_recieved] = '\0';
        std::cout << incomming_data_buffer << std::endl;

        const char *msg = "Niladri Das I am the Server";
        const char *msg1 = "Press f exactly four times";
        int len1;
        int len;
        ssize_t bytes_sent;
        ssize_t bytes_sent1;
        len = strlen(msg);
        len1 = strlen(msg1);
//-----------------------------------------------------------------------------------
//		printf(">>> ");

//		std::cin.getline(incomming_data_buffer, line);
        line = std::string(incomming_data_buffer);
        std::cout << incomming_data_buffer << std::endl;
        switch (line[0]) {
        case 'j':
            moveToStr(wam, &jp, "joint positions", line.substr(1));
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);
            break;
        case 'f':
            std::getline(file_jp,line_jp);
            {
                moveToStr(wam, &jp, "joint positions", line_jp);

            }
            std::cout << "sending back a message..." << std::endl;
            bytes_sent1 = send(new_sd, msg1, len1, 0);
            break;

        case 'p':
            moveToStr(wam, &cp, "tool position", line.substr(1));
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);
            break;

        case 'M':
            std::cout << "send()ing back a message..."  << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);
            break;

        case 'h':
            std::cout << "Moving to home position: "
                      << wam.getHomePosition() << std::endl;
            wam.moveHome();
            std::cout << "sending back a message" << std::endl;
            bytes_sent = send(new_sd, msg, len,0);
            break;

        case 'i':
            printf("WAM idled.\n");
            wam.idle();
            std::cout << "sending back a message" << std::endl;
            bytes_sent = send(new_sd, msg, len,0);
            break;
        case 'o':
            hand->initialize();
            //			hand->close(Hand::GRASP);
            //			hand->open(Hand::GRASP);
            //		   	hand->close(Hand::SPREAD);
            //		   	hand->trapezoidalMove(Hand::jp_type(M_PI/2.0),1, Hand::GRASP);
            //		   	hand->trapezoidalMove(Hand::jp_type(M_PI/2.0), Hand::GRASP);
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;

        case 'a':
            //			hand->initialize();
            hand->close(Hand::SPREAD);
            //			hand->close(Hand::GRASP);
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;

        case 'c':
            //			hand->initialize();
            hand->close(Hand::GRASP);
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;

        case 'd':
            //					hand->initialize();
            hand->open(Hand::SPREAD);
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;

        case 'e':
            //							hand->initialize();
            hand->open(Hand::GRASP);
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;

        case 'b':
            hand->trapezoidalMove(Hand::jp_type(M_PI/2.0), Hand::GRASP);
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;


        case 't':
            hand->trapezoidalMove(Hand::jp_type((M_PI)/6.0), Hand::GRASP);
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;

        case 'm':
            //			temp_str = line.substr(2);
            iss2.clear();
            iss2.str("");
            iss2.str(line.substr(2)) ;
            iss2 >> angle_degree;
            //			std::cin >> angle_degree;
            angle_radian = angle_degree*(M_PI/180);
            hand->trapezoidalMove(Hand::jp_type(angle_radian), Hand::GRASP);
            std::cout << angle_degree << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);
            break;


        case 'q':
        case 'x':
            printf("Quitting.\n");
            going = false;
            std::cout << "sending back a message..." << std::endl;
            bytes_sent = send(new_sd, msg, len, 0);

            break;

        default:
            if (line.size() != 0) {
                printf("Unrecognized option.\n");
                std::cout << "sending back a message..." << std::endl;
                bytes_sent = send(new_sd, msg, len, 0);

                printMenu();
            }
            break;
        }
        std::cout << "While loop complete" << std::endl;
    }


    wam.idle();
    pm.getSafetyModule()->waitForMode(SafetyModule::IDLE);

//-----------------------------------------------------------------------------
    freeaddrinfo(host_info_list);
    close(new_sd);
    close(socketfd);

//-----------------------------------------------------------------------------
    return 0;
}
Пример #19
0
void QTVS_Leap::ParangusGestureLogic()
{
  if (ui.checkBox_PalmForSwipes->isChecked())
  {

    Leap::Vector palmPosition = controller.frame(3).hands()[0].palmPosition();

    float previousPalmYPosAndDifference = palmPosition.y;
    float previousPalmXPosAndDifference = palmPosition.x;

    previousPalmYPosAndDifference = hand.palmPosition().y - previousPalmYPosAndDifference;
    previousPalmXPosAndDifference = hand.palmPosition().x - previousPalmXPosAndDifference;

    // std::cout << previousFingerXPosAndDifference << "\n";

    if (previousPalmYPosAndDifference < -2.5 && handCache.bGestureToggle)
    {
      std::cout << "down \n";
      handCache.bGestureToggle = false;
      QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, NULL, swipe_Down);
    }

    if (previousPalmYPosAndDifference > 2.5 && handCache.bGestureToggle)
    {
      std::cout << "swipe_Up \n";
      handCache.bGestureToggle = false;
      QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, NULL, swipe_Up);
    }

    if (previousPalmXPosAndDifference < -2.5 && handCache.bGestureToggle)
    {
      std::cout << "swipe_Left \n";
      handCache.bGestureToggle = false;
      QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, NULL, swipe_Left);
    }

    if (previousPalmXPosAndDifference > 2.5 && handCache.bGestureToggle)
    {
      std::cout << "swipe_Right \n";
      handCache.bGestureToggle = false;
      QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, NULL, swipe_Right);
    }


    if (!handCache.bGestureToggle &&
        abs(previousPalmYPosAndDifference) <= 0.5 &&
        abs(previousPalmXPosAndDifference) <= 0.5 )
      handCache.bGestureToggle = true;
    return;
  }

  // if palm for swipes isn't checked, we go for fingers instead:
  for (FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl)
  {
    const Finger finger = *fl;

//To simplify things down the road
    int leapFingerIndex = finger.type();

    if (finger.isExtended())
    {
      Leap::Vector fingerPosition = controller.frame(3).fingers()[leapFingerIndex].stabilizedTipPosition();

      float previousFingerYPosAndDifference = fingerPosition.y;
      float previousFingerXPosAndDifference = fingerPosition.x;

      previousFingerYPosAndDifference = finger.stabilizedTipPosition().y - previousFingerYPosAndDifference;
      previousFingerXPosAndDifference = finger.stabilizedTipPosition().x - previousFingerXPosAndDifference;

      // std::cout << previousFingerXPosAndDifference << "\n";

      if (previousFingerYPosAndDifference < -10 && handCache.fingers_p[leapFingerIndex].bGestureToggle)
      {
        handCache.fingers_p[leapFingerIndex].bGestureToggle = false;
        QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, leapFingerIndex, swipe_Down);
      }

      if (previousFingerYPosAndDifference > 10 && handCache.fingers_p[leapFingerIndex].bGestureToggle)
      {
        handCache.fingers_p[leapFingerIndex].bGestureToggle = false;
        QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, leapFingerIndex, swipe_Up);
      }

      if (previousFingerXPosAndDifference < -10 && handCache.fingers_p[leapFingerIndex].bGestureToggle)
      {
        handCache.fingers_p[leapFingerIndex].bGestureToggle = false;
        QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, leapFingerIndex, swipe_Left);
      }

      if (previousFingerXPosAndDifference > 10 && handCache.fingers_p[leapFingerIndex].bGestureToggle)
      {
        handCache.fingers_p[leapFingerIndex].bGestureToggle = false;
        QtConcurrent::run(this, &QTVS_Leap::ParangusGesture, leapFingerIndex, swipe_Right);
      }


      if (!handCache.fingers_p[leapFingerIndex].bGestureToggle &&
          abs(previousFingerYPosAndDifference) <= 0.1 &&
          abs(previousFingerXPosAndDifference) <= 0.1 )
        handCache.fingers_p[leapFingerIndex].bGestureToggle = true;
    }
  }
}