Example #1
0
 def Network_broadcast_played_card(self, data):
     card = Card(data['card'][0], data['card'][1])
     card.show()
     self.cb.in_play[data['player']] = card
     if data['lead']:
         self.cb.lead_card = card
     self.grb.play_card(data['player'])
Example #2
0
    def test_aceBig2MemoryIsBiggest2PairMustWin(self):
        cards = self.__createCards(1,22, 4,22, 3,21, 2,21)
        aceBig2Memory = SimpleFelix.AceBig2Memory(cards)

        self.assertTrue(aceBig2Memory.isMustWin(Hand(self.__createCards(1,22, 4,22))))

        aceBig2Memory.remember(Hand([Card(4,22)]))

        self.assertTrue(aceBig2Memory.isMustWin(Hand(self.__createCards(1,22, 4,22))))

        aceBig2Memory.remember(Hand([Card(4,21)]))

        self.assertTrue(aceBig2Memory.isMustWin(Hand(self.__createCards(1,22, 4,22))))
Example #3
0
def test_random_shuffle(g):

    print('\n')
    print('# in pickup  :', len(g.pickup_deck))
    print('# in player0 :', len(g.players[0].in_hand))
    print('# in discard :', len(g.discard_pile))

    print('\n\n')
    print('Player 0 hand')
    ascii_version_of_cards(g.players[0].in_hand)

    print('\n\n..Changing game states, adding 4 and player 0 turn now..')
    g.active_card = Card('4', 'Hearts', 'playing')
    g.current_player = 0

    print('..Now playing card 0 (for player 0)..')
    g.players[0].execute_move(Move('Play', [0]))

    print('\n\nDiscard pile (should be old card 0)')
    ascii_version_of_cards(g.discard_pile.deck)

    print('\n\n')
    print('Player 0 hand now (should be down 1 card')
    ascii_version_of_cards(g.players[0].in_hand)

    print('\n\n')
    print('Discard pile:')
    for i in g.discard_pile.deck:
        print('		', i)

    print('\n\n')
    print('Pickup Deck:')
    for i in g.pickup_deck.deck:
        print('		', i)
Example #4
0
def prepare_hand(cards):

    hand = []
    for card in cards.split():
        f, s = card[:-1], card[-1]
        hand.append(Card(f, s))
    return hand
Example #5
0
    def test_aceBig2MemoryWithAllAceBig2(self):
        cards = self.__createCards(1,22, 3,22, 4,22, 2,22, 1,21, 3,21, 4,21, 2,21)
        aceBig2Memory = SimpleFelix.AceBig2Memory(cards)

        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(1,21)])))
        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(2,21)])))
        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(3,21)])))
        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(4,21)])))
        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(1,22)])))
        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(2,22)])))
        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(3,22)])))
        self.assertTrue(aceBig2Memory.isMustWin(Hand([Card(4,22)])))
Example #6
0
def lookupTracked(trackedCards, card):
    # look into known cards
    for p in trackedCards:
        # find correspond card by area
        if cardsOverlap(p, card):
            if p.name != card.name and p.proba > card.proba:
                # use prev values if prev probability was better
                return Card(p.name, p.proba, card.proba, card.rect, card.img,
                            card.time)
            break
    return card
Example #7
0
 def Network_hand_dealt(self, data):
     # Reverse hand order if player wants to sort it backwards.
     if self.sort_hand_ascending:
         data['hand'] = data['hand'][::-1]
     self.cb.get_hand(data['hand'])
     if data['trump_card']:
         self.cb.trump_card = Card(data['trump_card'][0],
                                   data['trump_card'][1])
         self.cb.trump_card.show()
     else:
         self.cb.trump_card = None
     self.grb.draw_new_hand(len(data['hand']))
Example #8
0
    def __hand(self, *arg):
        if len(arg) % 2 != 0:
            raise Exception('number of parameters must be even')

        cards = []
        i = 0
        while i < len(arg):
            suit = arg[i]
            i += 1
            num = arg[i]
            i += 1
            cards.append(Card(suit, num))

        return Hand(cards)
Example #9
0
def createCards(*arg):
    if len(arg) % 2 != 0:
        raise Exception('number of parameters must be even: %s')

    cards = []
    i = 0
    while i < len(arg):
        suit = arg[i]
        i += 1
        num = arg[i]
        i += 1
        cards.append(Card(suit, num))

    return cards
Example #10
0
    def __init__(self, game):
        Deck.__init__(self, game)

        # Create deck of playing cards
        for i in ['Hearts', 'Diamonds', 'Spades', 'Clubs']:
            for j in [
                    '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack',
                    'Queen', 'King', 'Ace'
            ]:
                to_append = [Card(j, i, 'playing')] * 2
                self.add_cards(to_append)

        # Generate coloured UNO CARDS
        for i in ['Red', 'Yellow', 'Green', 'Blue']:
            for j in ['Skip', 'Reverse', "Draw 2"]:
                to_append = [Card(j, i, 'uno')] * 2
                self.add_cards(to_append)

        # Generate Draw 4 cards
        for i in range(4):
            self.add_cards([Card('Draw 4', 'Black', 'uno')])

        # Shuffle pickup deck
        shuffle(self.deck)
Example #11
0
 def handle_play_card(self, player: str, card: list, lead=False):
     self.send_all({
         'action': "broadcast_played_card",
         'player': player,
         'card': card,
         'lead': lead
     })
     self.gb.play_card(player,
                       Card(card[0], card[1]),
                       lead=True if len(self.gb.in_play) == 0 else False)
     if (len(self.gb.in_play) != 4):
         self.next_to_play_idx = (self.next_to_play_idx + 1) % 4
         self.send_all({
             'action': "broadcast_current_actor",
             'actor': self.gb.players[self.next_to_play_idx],
             'hand_num': self.hand_num
         })
         self.send_one(self.gb.players[self.next_to_play_idx], {
             'action': "play_card",
             'lead': False
         })
     else:
         self.finish_trick()
Example #12
0
    for card in cards:
        cardStrs.append('%s,%s ' % (card.suit, card.num))

    cardStr = ','.join(cardStrs)
    print 'cards = self.__createCards(%s)' % cardStr



nums = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 21, 22]
suits = [1, 2, 3, 4]

allCards = []

for suit in suits:
    for num in nums:
        allCards.append(Card(suit, num))


#printCardStr(cards)

i = 0
while 1:
    i += 1
    os.system('clear')
    print i

    cards = random.sample(allCards, 13)
    print cards

    felix = SimpleFelix()
Example #13
0
    def do_move(self, player, move):
        # This method should always return a list

        action, is_valid = self.is_valid_move(player, move)
        cards = move.cards

        if is_valid:
            # If we are drawing, pop top cards off pickup and return them
            # to let the player deal with putting them in their hand
            if action == 'Draw':
                cards = self.pickup_deck.give_top_cards(cards)
                self.active_draw_card = None
                self.no_to_draw = 0
                self.players[player].picked_up = True

            # Change key game states
            elif action == 'Play':

                num_cards = len(cards)
                value = cards[0].value

                # Want to check how many of the same cards we have played, and correct count
                # but in case where its an empty deck we look out
                if len(self.discard_pile.deck) > 0:
                    if value == self.discard_pile.deck[0].value:
                        self.same_active_cards += num_cards
                    else:
                        self.same_active_cards = num_cards
                else:
                    self.same_active_cards = num_cards

                self.discard_pile.add_cards(cards)

                # If we play a 3 we don't want to change anything, it is a pass card
                if value == '3':
                    pass

                # Change draw card if playing draw card
                elif value == 'Draw 2' or value == 'Draw 4':
                    self.active_draw_card = cards[0]
                    self.no_to_draw += int(value[-1:]) * num_cards

                # For each skip card, skip one player
                elif value == 'Skip' or value == 'Queen':
                    for i in cards:
                        if self.reverse is False:
                            self.current_player += 1
                        else:
                            self.current_player -= 1

                    # don't update active card for skip but we need to do it for queen
                    if value == 'Queen':
                        self.active_card = cards[0]

                # For each reverse card, toggle self.reverse
                elif value == 'Reverse':
                    # If we are down to 2 players, treat reverse as skip
                    if self.no_players == 2:
                        self.current_player += 1  # Only two players so don't care about direction
                    # Otherwise play it as normal
                    else:
                        for i in cards:
                            self.reverse = not self.reverse

                # Change active card if playing card, include 7 and 2 in here (10 will go to burn)
                elif cards[0].type == 'playing':
                    # if we are playing on the first turn, make current player the person who played the 4
                    if self.active_card == '':
                        self.current_player = player

                    self.active_card = cards[0]

                # We want to return empty list as we successfully played the cards
                cards = []

            elif action == 'Burn':
                self.discard_pile.add_cards(cards)
                self.discard_pile.burn()
                self.active_card = Card(
                    '4', 'PHANTOM',
                    'playing')  # Anything can be played on this
                self.same_active_cards = 0
                self.active_draw_card = None
                self.no_to_draw = 0

                # set ourselves as current, then step forward or back
                # so when we step again later it will still be us
                self.current_player = player  # need this for out of turn burns
                if self.reverse is False:
                    self.current_player -= 1
                else:
                    self.current_player += 1

                # As we burned, return empty list
                cards = []

            elif action == 'Pickup':
                cards = self.discard_pile.pick_up()
                self.active_card = Card(
                    '4', 'PHANTOM',
                    'playing')  # Set a phantom playing card to play on
                self.same_active_cards = 0
                self.players[player].picked_up = True

            # Change current player and current turn
            self.current_turn += 1
            if self.reverse is False:
                self.current_player = (self.current_player +
                                       1) % self.no_players
            else:
                self.current_player = (self.current_player -
                                       1) % self.no_players

        else:
            # If we unsuccessfully tried to draw, return nothing
            if action == 'Draw':
                cards = []

        return is_valid, cards
Example #14
0
 def reshuffle(self):
     self.ended = False
     self._deck = Card.getRandomDeck()
     if (self._rounds == None):
         self._rounds = []
     self.nextRound()
Example #15
0
def desk_card_info(request):
    from common.card import Card

    if not request.GET:
        # 说明是第一次进
        return render(request, 'desk_card_info.html',
                      dict(form=DeskQueryForm()))

    form = DeskQueryForm(request.GET)
    if not form.is_valid():
        return render(request, 'desk_card_info.html', dict(form=form))

    dst_desk = load_desk(form.cleaned_data['desk_id'])
    if not dst_desk:
        return render(request, 'desk_card_info.html',
                      dict(form=form, result='no such desk'))

    if dst_desk.status != config.GAME_STATE_INGAME:
        return render(request, 'desk_card_info.html',
                      dict(form=form, result='game not begin'))

    share_cards = [Card(num).human_str for num in dst_desk.share_cards]
    _list = []
    if dst_desk.send_card_uin:
        is_send_card = True
        extend_card = Card(dst_desk.extend_card).human_str
        current_uin = dst_desk.send_card_uin
    else:
        is_send_card = False
        current_player = dst_desk.player_group.get_player_by_uin(
            dst_desk.recv_card_uin)
        extend_card = current_player.card_group.card_list[-1].human_str
        current_uin = dst_desk.recv_card_uin

    for player in dst_desk.player_group.active_players:
        _list.append(
            dict(
                belong=u'%s-%s' % (player.user.nick, player.uin),
                cards=[
                    p_card.human_str for p_card in player.card_group.card_list
                ],
                out_cards=[
                    p_card.human_str
                    for p_card in player.card_group.out_card_list
                ],
                dis_cards=[
                    p_card.human_str
                    for p_card in player.card_group.discard_list
                ],
                op_list=player.op_list,
                op_type=player.op_type if not player.need_wait else None,
            ))

    return render(
        request, 'desk_card_info.html',
        dict(
            form=form,
            card_list=_list,
            share_cards_list=share_cards,
            is_send_card=is_send_card,
            extend_card=extend_card,
            current_uin=current_uin,
        ))
Example #16
0
    def _recognizeFrame(self, frame):
        # resize image, then use for getting blob
        frameSized = cv2.resize(frame, (300, 300))

        # construct a blob from the image
        imageBlob = cv2.dnn.blobFromImage(frameSized,
                                          1.0, (300, 300),
                                          (104.0, 177.0, 123.0),
                                          swapRB=False,
                                          crop=False)

        # apply OpenCV's deep learning-based face detector to localize
        # faces in the input image
        self.detector.setInput(imageBlob)
        detections = self.detector.forward()

        frameCards = []
        frameH, frameW = frame.shape[:2]
        # loop over the detections
        for i in range(0, detections.shape[2]):
            # extract the confidence (i.e., probability) associated with
            # the prediction
            confidence = detections[0, 0, i, 2]

            # filter out weak detections
            if confidence > self.confidence:
                # compute the (x, y)-coordinates of the bounding box for
                # the face
                box = detections[0, 0, i, 3:7] * np.array(
                    [frameW, frameH, frameW, frameH])
                startX, startY, endX, endY = box.astype("int")

                b = 40
                sY = startY - b if startY - b > 0 else 0
                eY = endY + b if endY + b <= frameH else frameH
                sX = startX - b if startX - b > 0 else 0
                eX = endX + b if endX + b <= frameW else frameW
                cardImg = frame[sY:eY, sX:eX]

                card = Card("", 0, 0, (startX, startY, endX, endY), cardImg,
                            datetime.now())
                if self.getActionLevel() == 2:

                    # extract the face ROI
                    face = frame[startY:endY, startX:endX]
                    fH, fW = face.shape[:2]

                    # ensure the face width and height are sufficiently large
                    if fW < 20 or fH < 20:
                        continue

                    # construct a blob for the face ROI, then pass the blob
                    # through our face embedding model to obtain the 128-d
                    # quantification of the face
                    faceBlob = cv2.dnn.blobFromImage(face,
                                                     1.0 / 255, (96, 96),
                                                     (0, 0, 0),
                                                     swapRB=True,
                                                     crop=False)
                    self.embedder.setInput(faceBlob)
                    vec = self.embedder.forward()

                    # perform classification to recognize the face
                    preds = self.recognizer.predict_proba(vec)[0]
                    j = np.argmax(preds)
                    proba = preds[j]
                    name = self.lencoder.classes_[j]

                    card = Card(name, proba, proba,
                                (startX, startY, endX, endY), cardImg,
                                datetime.now())
                    card = lookupTracked(self.trackedCards, card)

                frameCards.append(card)
        return frameCards
Example #17
0
def test_power_cards(g):

    print('\n\n..Changing game states, adding 4 and player 0 turn now..')
    g.active_card = Card('4', 'Hearts', 'playing')
    g.current_player = 0

    print('\n\n..Initialise player 0s hand')
    g.players[0].in_hand = [
        # Play 5
        Card('5', 'Hearts', 'playing'),
        # Play 7 on 7
        Card('7', 'Hearts', 'playing'),
        Card('7', 'Hearts', 'playing'),
        # Burn with four 6
        Card('6', 'Hearts', 'playing'),
        Card('6', 'Hearts', 'playing'),
        Card('6', 'Hearts', 'playing'),
        Card('6', 'Hearts', 'playing'),
        # Play 4
        Card('4', 'Hearts', 'playing'),
        # Skip and reverse
        Card('Skip', 'Red', 'uno'),
        Card('Reverse', 'Red', 'uno'),
        # Stack Draw 2
        Card('Draw 2', 'Red', 'uno'),
        Card('3', 'Hearts', 'playing'),
        Card('Draw 2', 'Red', 'uno'),
        # Pickup 4
    ]
    ascii_version_of_cards(g.players[0].in_hand)

    print('\n\n..Playing 5, [7, 7], [6, 6, 6]')
    g.players[0].execute_move(Move('Play', [0]))
    g.current_player = 0
    g.players[0].execute_move(Move('Play', [0, 1]))
    g.current_player = 0
    g.players[0].execute_move(Move('Play', [0, 1, 2]))
    print('\n Player 0:')
    ascii_version_of_cards(g.players[0].in_hand)
    print('Discard pile:')
    ascii_version_of_cards(g.discard_pile.deck)

    print('\n\n..Playing 6 (out of turn), 4')
    for i in range(2):
        g.players[0].execute_move(Move('Play', [0]))
        g.current_player = 0
    print('\n Player 0:')
    ascii_version_of_cards(g.players[0].in_hand)
    print('Discard pile:')
    ascii_version_of_cards(g.discard_pile.deck)
    print('Burned pile:')
    ascii_version_of_cards(g.burned_pile.deck)

    print('\n\n..Playing Skip and Reverse')
    for i in range(2):
        print('Playing:', g.players[0].in_hand[0].value, end=' == ')
        g.players[0].execute_move(Move('Play', [0]))
        print('Current player:', g.current_player)
        g.current_player = 0
    print('\n Player 0:')
    ascii_version_of_cards(g.players[0].in_hand)
    print('Discard pile:')
    ascii_version_of_cards(g.discard_pile.deck)
    print('Burned pile:')
    ascii_version_of_cards(g.burned_pile.deck)

    print('\n\n..Playing Draw 2, 3, Draw 2')
    for i in range(3):
        g.players[0].execute_move(Move('Play', [0]))
        g.current_player = 0
    print('\n Player 0:')
    ascii_version_of_cards(g.players[0].in_hand)
    print('Discard pile:')
    ascii_version_of_cards(g.discard_pile.deck)
    print('Burned pile:')
    ascii_version_of_cards(g.burned_pile.deck)

    print('\n\n..Drawing 4 cards')
    g.players[0].execute_move(Move('Draw', 4))
    print('\n Player 0:')
    print('In hand')
    ascii_version_of_cards(g.players[0].in_hand)
    print('Face down')
    ascii_version_of_cards(g.players[0].face_down)
    print('Discard pile:')
    ascii_version_of_cards(g.discard_pile.deck)
    print('Burned pile:')
    ascii_version_of_cards(g.burned_pile.deck)