Esempio n. 1
0
 def setup(self):
     words = "abcdefghijklmnopqrstuvwxy"
     for i in range(25):
         card = Card()
         card.setWord(words[i])
         self.ids.grid.add_widget(card)
         self.cards.append(card)
Esempio n. 2
0
 def __init__(self,channel_id,card_number):
     Card.__init__(self,channel_id,card_number)
     for port_id in range(14):
         self.in_ports.append(InPort(channel_id,card_number,port_id,0))
         self.out_ports.append(OutPort(channel_id,card_number,port_id,0))
     self.raw_out_ports = '00'
     self.raw_in_ports = '00'
Esempio n. 3
0
    def __init__(self, name, 
                 imageFileName = None,
                 struggles = None,
                 *args, **kwargs):
        Card.__init__(self, name, imageFileName, *args, **kwargs)
        if imageFileName != None:
            self.image = StoryImage(imageFileName)
        self.committed = {}
        self.success = {}
        self.rect = {}
        self.game = None
        self.Player1 = None
        self.Player2 = None

        if struggles is None:
            struggles = []
            struggles.append(TerrorStruggle())
            struggles.append(CombatStruggle())
            struggles.append(ArcaneStruggle())
            struggles.append(InvestigationStruggle())
            struggles.append(SkillStruggle())

        for struggle in struggles:
            struggle.addToStory(self)
        self.struggles = struggles
Esempio n. 4
0
    def setCard(self, card):
        """
        Set card as dictionary

            card: (dict) -- Dictionary of card

        Format:
        {"name":      <card name>,
         "lines":    (line1,
                      line2,
                       ...),
         "arg":       <argument>}

        Example:
        {"name":      "k_points",
         "lines":     ("4 4 4 1 1 1",),
         "arg":       "automatic"}
        """
        if not card:    # Ignore empty card 
            return

        self._checkDictFormat(card, CARD_KEYS, CARD_REQ)
        
        c       = Card( card["name"],
                        arg = ifelse(card.has_key("arg"), card.get("arg"), None))
        if card.has_key("lines"):
            c.setLines(card["lines"])
            
        self._fcards.append(c)
Esempio n. 5
0
 def _initiate_opening_hands(self):
     for rank in Card.STR_RANKS:
         for suit,val in Card.CHAR_SUIT_TO_INT_SUIT.items():
             John._FULL_DECK.append(Card.new(rank + suit))
     for combo in itertools.combinations(John._FULL_DECK, 2):
         John._ALL_HOLE_CARDS.append(combo)
         cards = Card.int_to_str(combo[0]) + Card.int_to_str(combo[1])
         c1_rank, c1_suit, c2_rank, c2_suit = cards
         # Check for pairs
         if c1_rank == c2_rank:
             for rank in Card.STR_RANKS:
                 if c1_rank == rank:
                     if rank not in John._PAIRS:
                         John._PAIRS[rank] = set()
                     John._PAIRS[rank].add(combo)
         else:
             for rank_pair in itertools.combinations(Card.STR_RANKS[::-1], 2):
                 ranks = rank_pair[0] + rank_pair[1]
                 if rank_pair == (c2_rank, c1_rank) or rank_pair == (c1_rank, c2_rank):
                     if c1_suit == c2_suit:  # Suited!
                         if ranks not in John._SUITED:
                             John._SUITED[ranks] = set()
                         John._SUITED[ranks].add(combo)
                         if Card.STR_RANKS.index(rank_pair[0]) == 1 + Card.STR_RANKS.index(rank_pair[1]):
                             if ranks not in John._SUITED_CONNECTORS:
                                 John._SUITED_CONNECTORS[ranks] = set()
                             John._SUITED_CONNECTORS[ranks].add(combo)
                         # DEBUGGING
                         # print(ranks, Card.int_to_str(combo[0]), Card.int_to_str(combo[1]))
                     else:
                         if ranks not in John._UNSUITED:
                             John._UNSUITED[ranks] = set()
                         John._UNSUITED[ranks].add(combo)
Esempio n. 6
0
 def __parse_card_item(self, text):
     card = Card()
     card.multiverseid = int(multiverseid_re.search(text).group(1))
     card.name = name_re.search(text).group(1)
     card.language = LANG_DICT[language_re.search(text).group(1)]
     # other attributes are set by Card.add_translation()
     return card
Esempio n. 7
0
    def _convertCards(self, cards):
        for cname in cards.keys():
            c   = Card(cname)
            c.setArg(cards[cname]["args"])
            for l in cards[cname]["values"]:
                c.addLine(l)

            self.cards[cname]    = c
Esempio n. 8
0
 def __setattr__(self,name,value):
     port = re.match('^port_(\d+)', name) 
     if port  :
         port_pos = int((port.groups())[0])
         self.__pending_write = 1 
         self.__out_ports[port_pos] = str(value)
     else:
         Card.__setattr__(self,name,value)
Esempio n. 9
0
 def __init__(self,id,serial):
     Card.__init__(self,id,serial)
     self.id = id
     self.__in_ports = ['0']*14
     self.__out_ports = ['0']*14
     self.__raw_out_ports = ''
     self.__raw_in_ports = ''
     self.__pending_write = 0
Esempio n. 10
0
def test_basicCardCreation():
	"""
	Create some basic cards and make sure they come out ok.
	"""
	c = Card("A","Diamond")
	assert c.getName() == "A"
	assert c.getValue() == [1,11]
	assert c.getSuit() == "Diamond"
Esempio n. 11
0
 def _validate(self):
     all_cards = set()
     for hand in self.hands:
         for suit in SUITS:
             for card in hand.cards_in_suit(suit):
                 card_identifier = Card.identifier_for_card(suit, card)
                 assert card_identifier not in all_cards, ("Already seen %s" % Card.card_name(suit, card))
                 all_cards.add(card_identifier)
     assert len(all_cards) == 52
Esempio n. 12
0
 def test_value_setter_invalid(self):
     invalid_values = ['Kings', 'Jack', 'Queen', '0', -1, 0, 14, random.randint(15,100), random.randint(-100, -1)]
     for value in invalid_values:
         card = Card(3, "diamonds")
         try:
             card.value = value
             self.assert_(False)
         except ValueError as e:
             self.assert_(isinstance(e, ValueError))
Esempio n. 13
0
 def draw(self, pos):
     Card.draw(self, pos)
     x,y = pos
     for i in range(self.success[self.Player1]):
         pos = x + i*TOKENEDGE, y+CARDWIDTH-TOKENEDGE
         self.successTokenBag[i].draw(pos)
     for i in range(self.success[self.Player2]):
         pos = x + i*TOKENEDGE, y
         self.successTokenBag[i+5].draw(pos)
Esempio n. 14
0
def step_given(context, suit1, no1, suit2, no2, suit3, no3, suit4, no4, suit5, no5):
    sut = PokerGame()
    sut.setUp(
        Card.get(suit1, int(no1)),
        Card.get(suit2, int(no2)),
        Card.get(suit3, int(no3)),
        Card.get(suit4, int(no4)),
        Card.get(suit5, int(no5)),
    )
    context.sut = sut
Esempio n. 15
0
 def prompt_add_card(self):
     new_card = Card()
     for dimension in self.dimensions:
         state = ""
         while len(state) == 0:
             state = raw_input("Enter value for " + dimension + ">> ")
         # Adds state at dimension for the new card
         new_card.add_dimension(dimension, state.lower().strip())
     # Add the new card to the colleciton
     self.collection.append(new_card)
Esempio n. 16
0
    def __init__(self):
        self.cardfile = bsddb.hashopen("./data/card_images.db", "c")
        self.back = pyglet.resource.texture("back.jpg")
        self.notfound = pyglet.resource.texture("notfound.jpg")
        self.combat = pyglet.resource.texture("combat.png")
        self.triggered = pyglet.resource.texture("triggered.png")
        self.activated = pyglet.resource.texture("activated.png")

        # XXX This is a hack
        Card.build_fbo()
Esempio n. 17
0
    def test_qeinput_card(self):
        input   = QEInput()
        c       = Card("atomic_species")
        c.setArg("temp")
        c.addLine("Ni  26.98  Ni.pbe-nd-rrkjus.UPF")
        input.addCard(c)
        c2      = input.card("atomic_positions")
        self.assertEqual(input.toString(), fixtures.assertNewCard)

        input.removeCard("atomic_species")
        self.assertEqual(input.toString(), fixtures.assertNewCard2)
Esempio n. 18
0
	def scoreLines(self, playedCard, r, c):
		lines = self.validLines(r,c)
		score = len([(card1,card2) for (cell1,cell2) in lines 
					for card1 in self.getCardsInCell(*cell1)
					for card2 in self.getCardsInCell(*cell2)
					if Card.isSet(playedCard, card1, card2)])
		stack = self.getCardsInCell(r,c)
		if len(stack)==self.cellSize:
			if Card.isSet(*stack):
				score+=1
		return score
Esempio n. 19
0
 def from_hex_identifier(cls, identifier):
     hands = cls._empty_hands()
     hexChars = '0123456789abcdef'
     for charIndex, hexChar in enumerate(identifier):
         hexIndex = hexChars.index(hexChar)
         highHandIndex = hexIndex / 4
         lowHandIndex = hexIndex - highHandIndex * 4
         highSuit, highCard = Card.suit_and_value_from_identifier(charIndex * 2 + 0)
         lowSuit, lowCard = Card.suit_and_value_from_identifier(charIndex * 2 + 1)
         hands[highHandIndex][highSuit.index] += highCard
         hands[lowHandIndex][lowSuit.index] += lowCard
     return Deal(map(Hand, hands))
Esempio n. 20
0
 def __getattr__(self,name):
     port = re.match('^port_(in|out)_(\d+)', name) 
     if port :
         port_pos = int((port.groups())[1])
         type = (port.groups())[0]
         
         if type == 'in' :
             return int(self.__in_ports[port_pos])
         else:
             return int(self.__out_ports[port_pos])
     else:
         Card.__getattr__(self,name)
Esempio n. 21
0
    def test_card_remove_lines(self):
        c   = Card("atomic_positions")
        c.addLine(" Ni 0.00 0.00 0.00 ")
        c.addLine(" Ni 0.50 0.50 0.50 ")
        c.removeLine(0)
        self.assertEqual(c.line(0), "Ni 0.50 0.50 0.50")

        c.editLines(["a", "b"])
        self.assertEqual(c.lines(), ["a", "b"])
Esempio n. 22
0
 def test_value_setter(self):
     normal_card = Card(6, "hearts")
     self.assertEqual(normal_card.value, '6')
     self.assertEqual(normal_card.index, 6)
     normal_card.value = 10
     self.assertEqual(normal_card.value, '10')
     self.assertEqual(normal_card.index, 10)
     normal_card.value = 'J'
     self.assertEqual(normal_card.value, 'J')
     self.assertEqual(normal_card.index, Card.JACK_INDEX)
     normal_card.value = '4'
     self.assertEqual(normal_card.value, '4')
     self.assertEqual(normal_card.index, 4)
Esempio n. 23
0
    def read_hole_cards_line(self, hole_cards_line, active_player):
        """Read the two hole cards given to the active player in the hole card line. Analyses a single line (string).

        Args:
            hole_cards_line (str) : The hole card line, containing the name of the active player.
            active_player (Player) : The name of the active player.

         Returns:
            (list): A list of two Card, containing the two hole cards read.
        """

        # TODO: Does not read the 1st hand of a file

        if not active_player.name in hole_cards_line:
            raise Exception("The active player hole cards are missing.")

        in_cards = False
        card1 = Card(0, "")
        card2 = Card(0, "")

        for i in range(len(hole_cards_line)):
            if in_cards == True:
                card1.set_value(hole_cards_line[i])
                card1.color = hole_cards_line[i + 1]
                card2.set_value(hole_cards_line[i + 3])
                card2.color = hole_cards_line[i + 4]
                break

            if hole_cards_line[i] == "[":
                in_cards = True

        return [card1, card2]
Esempio n. 24
0
    def from_raw_to_ports(self,ports='in'):
        if ports == 'in' :
#             print "hago la conversion de raw a ports en read"
#             print self.raw_in_ports
            bin_data = Card.hex_to_bin(self.raw_in_ports)
            # los dos ultimos bits de los 2 bytes no sirven            
            Card.logger_instance.debug("from_raw_to_ports in: bin_data %s %s %s %s  hex_data %s" % (bin_data[0:4],bin_data[4:8],bin_data[8:12],bin_data[12:16],self.raw_in_ports))
            bin_data = bin_data[0:7] + bin_data[8:15]
            for port_id in range(len(self.in_ports)):
                self.in_ports[port_id].set_value(int(bin_data[port_id]))
        else:
            bin_data = Card.hex_to_bin(self.raw_out_ports)
            for port_id in range(len(self.out_ports)):
                self.out_ports[port_id].set_value(int(bin_data[port_id]))
Esempio n. 25
0
    def from_chars(cls, *args):
        """return a new object from pairs of character symbols

        works with either multiple arguments, or a single iterable
        """

        try:
            return cls(Card.from_chars(chars) for chars in args)
        except CardCreationError:
            try:
                return cls(Card.from_chars(chars) for chars in args[0])
            except (TypeError, CardCreationError):
                pass
            raise HandCreationError('invalid card symbols')
Esempio n. 26
0
 def __init__(self, fight, src = None):
     ''' Конструктор.
         Fight fight - битва, в которой участвует файтер.
         src - документ.
     '''
     if src:
         self.__dict__.update(src)
         self.deck = [Card.js_load(c) for c in self.deck]
         self.hand = [Card.js_load(c) for c in self.hand]
         self.stats = Stats(self.stats)
         self.effects = [Effect.js_load(eff, self) for eff in self.effects]
     else:
         self.id = unique_id()
         self.stats = Stats()
     self.fight = fight
Esempio n. 27
0
    def parse_showdown(self, parser, river):
        # search for showdown title
        parser.read_until(u'*** SHOW DOWN ***')

        # showdown title line processed -> advance to next line
        parser.read_line()

        hands = []

        # read until summary title concludes the showdown
        while u'*** SUMMARY ***' not in parser.cline:
            # skip mucked hands
            if u'(mucked)' not in parser.cline:
                try:
                    player = parser.before(':')

                    cards = Card.from_str(parser.between('[', ']'))
                    hand = Hand.from_cards(river + cards)

                    hands.append((hand, player))
                except ValueError:
                    pass

            # hand processed -> advance to next line
            parser.read_line()

        return hands
Esempio n. 28
0
 def lossUser(self,cardid):
     try:
     #更新卡片及用户状态
         cardmodel = Card()
         noid = cardmodel.getNoId(cardid)
         sql = 'update card set `stat` = 4 where noid = "'+str(noid['noid'])+'"'
         self._cursor.execute(sql)
         #更新用户状态及操作时间 
         carddata = cardmodel.queryCard(noid['noid'])
         uid = carddata['uid']
         sql = 'update customer set `stat` = 2,actdate=UNIX_TIMESTAMP() where id='+str(uid)
         self._cursor.execute(sql)
         self._conn.commit()
         return True
     except:
         return False
Esempio n. 29
0
def testCreateConfig():
    print "Testing creation of config file"
    qe  = QEInput()
    nl  = Namelist('control')
    nl.add('title', "'Ni'")
    nl.add('restart_mode', "'from_scratch'")
    print "Adding parameters to namelist:\n%s" % nl.toString()
    nl.set('title', "'Fe'")
    qe.addNamelist(nl)
    print "Adding namelist to QEInput:\n%s" % qe.toString()

    c = Card('atomic_species')
    c.addLine('Ni  26.98  Ni.pbe-nd-rrkjus.UPF')
    print "Adding line to card:\n%s" % c.toString()
    qe.addCard(c)
    print "Adding card to QEInput:\n%s" % qe.toString()
def main ():

     #Introduction
     print ("This program prints out n randomly generated playing cards. ")

     #Get input
     n = eval(input("\nHow many cards would you like? "))

     #Generate cards
     for i in range(n):
         rank = random.randrange(1, 13)
         suit = random.choice(["s", "h", "c", "d"])
         card = Card(rank, suit)
         print ()
         card.__str__()
         print ("The blackjack value of the card is", card.BJValue())
Esempio n. 31
0
def card_ints_to_str(cards):
    buildstring = []
    for c in cards:
        buildstring.append(Card.get_str(c))
    return "".join(buildstring)
Esempio n. 32
0
 def test_draw(self):
     self.assertEqual(self.acesDeck.draw(), Card(51))
     self.assertEqual(self.acesDeck.count(), 3)
Esempio n. 33
0
        self.hand.append(card)

    def dealershow(self) -> str:
        if len(self.hand) != 2:
            raise Exception(
                "Dealer should be holding two cards at this time...")
        return str(self.hand[0]) + " 🂠"

    def __str__(self):
        return " ".join([str(x) for x in self.hand])

    def sum(self) -> int:
        return sum([x.value() for x in self.hand])

    def dealersum(self) -> int:
        if len(self.hand) != 2:
            raise Exception(
                "Dealer should be holding two cards at this time...")
        return self.hand[0].value()


if __name__ == "__main__":
    #Test hand.py
    test = Hand()
    test.add(Card(1, 0))
    test.add(Card(5, 2))
    print(test)
    print(f"Total: {test.sum()}")
    test2 = Hand([Card(1, 2), Card(1, 3), Card(7, 1)])
    print(test2)
    print(f"Total: {test2.sum()}")
Esempio n. 34
0
def shuffle_list_of_cards():
    shuffled_deck = BELOTE_ALL_CARDS[::]
    random.shuffle(shuffled_deck)
    return [Card.from_string(card) for card in shuffled_deck]
Esempio n. 35
0
 def test_add_deck(self):
     self.fullDeck.add_deck(self.acesDeck)
     self.assertEqual(self.fullDeck.draw(), Card(51))
     self.assertEqual(self.fullDeck.draw(), Card(50))
     self.assertEqual(self.fullDeck.draw(), Card(49))
     self.assertEqual(self.fullDeck.draw(), Card(48))
Esempio n. 36
0
# -*- coding: utf-8 -*-
"""
Created on Mon Apr  1 07:42:51 2019

@author: Gerry
"""

from card import Card

card = Card()


class Logic:

    # card1 = hand
    # card2 = field

    def higherSingle(self, card1, card2):
        return (card.getCardValues(card1)[0] -
                card.getCardValues(card2)[0]) > 0

    def higherPair(self, cards1, cards2):
        return (card.getPairScore(cards1) - card.getPairScore(cards2)) > 0

    def higherCombo(self, cards1, cards2):
        return (card.getComboScore(cards1) - card.getComboScore(cards2)) > 0

    def legalCard(self, cards):
        return (card.isSingle(cards) or card.isPair(cards)
                or card.isCombo(cards))
Esempio n. 37
0
display_surface = pygame.display.set_mode((W, H))
image = pygame.image.load(r"/home/robuntu/Thomas/Server-Project/layout.py")
image = pygame.transform.scale(image, (900, 650))
center = Layout(190, 185, 441, 253)
private_hand = Layout(605, 480, 295, 170)  # NOTE THAT THE DECK CLASS PROB ISN'T THE MOST FITTING FOR THIS (Change later)
global_hand = []    # All card registered on the board

gear_regions = []  # Locations of gear hands (Gear regions do not actually store the cards in them)
gear_regions.append(Layout(188, 517, 338, 101))
gear_regions.append(Layout(707, 80, 117, 316))
gear_regions.append(Layout(212, 18, 349, 121))
gear_regions.append(Layout(13, 157, 89, 317))

# Add to Deck
door_deck = Deck(208, 209, 49, 89)
door_deck.add(Card(r"C:\Users\dannie\PycharmProjects\untitled\Images\Sun.png", 200, 200, 25, 40))
door_deck.add(Card(r"C:\Users\dannie\PycharmProjects\untitled\Images\Spaghetti_Jesus.png", 300, 200, 25, 40))
door_deck.add(Card(r"C:\Users\dannie\PycharmProjects\untitled\Images\FireHawk.png", 100, 200, 25, 40))
door_deck.randomize()

# Die
die = Dice(280, 210, 50, 50)

def update():
    # Check to see if Die is being rolled
    if 0 < die.rolling <= 50:   # Basically 50-micro rolls
        die.roll()
        die.rolling += 1
    else:   # Reset die to be not rolling (0 = False)
        die.rolling = 0
Esempio n. 38
0
 def __init__(self, num_cards = 2):
     Logger.log("Hand: Creating a new hand with cards: " + str(num_cards))
     self.hand = []
     for i in range(0, num_cards):
         Logger.log("Hand: Calling add_card(Card()).")
         self.add_card(Card())
Esempio n. 39
0
 def hand_to_string(self):
     Logger.log("Hand: Converting hand to string.")
     results = "[ "
     for i in range(0, 2):
         results += Card.translate(self.hand[i]) + " ], ["
     return results[:-3]
Esempio n. 40
0
    def run(self):
        player = self._build_player()
        context = zmq.Context()
        c2s_socket = context.socket(zmq.PUSH)
        c2s_socket.setsockopt(zmq.IDENTITY, self.identity)
        c2s_socket.set_hwm(10)
        c2s_socket.connect(self.c2s)

        s2c_socket = context.socket(zmq.DEALER)
        s2c_socket.setsockopt(zmq.IDENTITY, self.identity)
        s2c_socket.connect(self.s2c)

        player.reset()
        # init_cards = np.arange(52)
        # init_cards = np.append(init_cards[::4], init_cards[1::4])
        # player.prepare_manual(init_cards)
        player.prepare()
        r, is_over = 0, False
        lstm_state = np.zeros([1024 * 2])
        while True:
            role_id = player.get_role_ID()
            if role_id in ROLE_IDS_TO_TRAIN:
                prob_state, all_state, curr_handcards_value, last_cards_value, last_category = \
                    player.get_state_prob(), player.get_state_all_cards(), player.get_curr_handcards(), player.get_last_outcards(), player.get_last_outcategory_idx()
                prob_state = np.concatenate(
                    [Card.val2onehot60(curr_handcards_value), prob_state])
                # after taking the last action, get to this state and get this reward/isOver.
                # If isOver, get to the next-episode state immediately.
                # This tuple is not the same as the one put into the memory buffer

                is_active = False if last_cards_value.size > 0 else True
                mask = get_mask(
                    to_char(curr_handcards_value), action_space,
                    None if is_active else to_char(last_cards_value))
                if is_active:
                    mask[0] = 0
                last_two_cards = player.get_last_two_cards()
                last_two_cards_onehot = np.concatenate([
                    Card.val2onehot60(last_two_cards[0]),
                    Card.val2onehot60(last_two_cards[1])
                ])
                c2s_socket.send(dumps(
                    (self.identity, role_id, prob_state, all_state,
                     last_two_cards_onehot, mask, 0 if is_active else 1,
                     lstm_state, r, is_over)),
                                copy=False)
                action_idx, lstm_state = loads(
                    s2c_socket.recv(copy=False).bytes)

                r, is_over, _ = player.step_manual(
                    to_value(action_space[action_idx]))
            else:
                _, r, _ = player.step_auto()
                is_over = (r != 0)
            if is_over:
                # print('{} over with reward {}'.format(self.identity, r))
                # logger.info('{} over with reward {}'.format(self.identity, r))
                # sys.stdout.flush()
                player.reset()
                player.prepare()
                lstm_state = np.zeros([1024 * 2])
Esempio n. 41
0
 def step(self, action):
     if self.act == ACT_TYPE.PASSIVE:
         if self.mode == MODE.PASSIVE_DECISION:
             if action == 0 or action == 2:
                 self.finished = True
                 if action == 2:
                     self.intention = np.array([16, 17])
                     self.card_type = Category.BIGBANG.value
                 else:
                     self.card_type = Category.EMPTY.value
                 return
             elif action == 1:
                 self.mode = MODE.PASSIVE_BOMB
                 return
             elif action == 3:
                 self.mode = MODE.PASSIVE_RESPONSE
                 return
             else:
                 raise Exception('unexpected action')
         elif self.mode == MODE.PASSIVE_BOMB:
             # convert to value input
             self.intention = np.array([action + 3] * 4)
             self.finished = True
             self.card_type = Category.QUADRIC.value
             return
         elif self.mode == MODE.PASSIVE_RESPONSE:
             self.intention = give_cards_without_minor(
                 action, self.last_cards_value, self.category, None)
             if self.category == Category.THREE_ONE.value or \
                     self.category == Category.THREE_TWO.value or \
                     self.category == Category.THREE_ONE_LINE.value or \
                     self.category == Category.THREE_TWO_LINE.value or \
                     self.category == Category.FOUR_TAKE_TWO.value:
                 if self.category == Category.THREE_TWO.value or self.category == Category.THREE_TWO_LINE.value:
                     self.minor_type = 1
                 self.mode = MODE.MINOR_RESPONSE
                 # modify the state for minor cards
                 discard_onehot_from_s_60(self.prob_state,
                                          Card.val2onehot60(self.intention))
                 self.minor_length = get_seq_length(self.category,
                                                    self.last_cards_value)
                 if self.minor_length is None:
                     self.minor_length = 2 if self.category == Category.FOUR_TAKE_TWO.value else 1
                 self.card_type = self.category
                 return
             else:
                 self.finished = True
                 self.card_type = self.category
                 return
         elif self.mode == MODE.MINOR_RESPONSE:
             minor_value_cards = [action + 3
                                  ] * (1 if self.minor_type == 0 else 2)
             # modify the state for minor cards
             discard_onehot_from_s_60(self.prob_state,
                                      Card.val2onehot60(minor_value_cards))
             self.intention = np.append(self.intention, minor_value_cards)
             assert self.minor_length > 0
             self.minor_length -= 1
             if self.minor_length == 0:
                 self.finished = True
                 return
             else:
                 return
     elif self.act == ACT_TYPE.ACTIVE:
         if self.mode == MODE.ACTIVE_DECISION:
             self.category = action + 1
             self.active_decision = action
             self.mode = MODE.ACTIVE_RESPONSE
             self.card_type = self.category
             return
         elif self.mode == MODE.ACTIVE_RESPONSE:
             if self.category == Category.SINGLE_LINE.value or \
                     self.category == Category.DOUBLE_LINE.value or \
                     self.category == Category.TRIPLE_LINE.value or \
                     self.category == Category.THREE_ONE_LINE.value or \
                     self.category == Category.THREE_TWO_LINE.value:
                 self.active_response = action
                 self.mode = MODE.ACTIVE_SEQ
                 return
             elif self.category == Category.THREE_ONE.value or \
                     self.category == Category.THREE_TWO.value or \
                     self.category == Category.FOUR_TAKE_TWO.value:
                 if self.category == Category.THREE_TWO.value or self.category == Category.THREE_TWO_LINE.value:
                     self.minor_type = 1
                 self.mode = MODE.MINOR_RESPONSE
                 self.intention = give_cards_without_minor(
                     action, np.array([]), self.category, None)
                 # modify the state for minor cards
                 discard_onehot_from_s_60(self.prob_state,
                                          Card.val2onehot60(self.intention))
                 self.minor_length = 2 if self.category == Category.FOUR_TAKE_TWO.value else 1
                 return
             else:
                 self.intention = give_cards_without_minor(
                     action, np.array([]), self.category, None)
                 self.finished = True
                 return
         elif self.mode == MODE.ACTIVE_SEQ:
             self.minor_length = action + 1
             self.intention = give_cards_without_minor(
                 self.active_response, np.array([]), self.category,
                 action + 1)
             if self.category == Category.THREE_ONE_LINE.value or \
                     self.category == Category.THREE_TWO_LINE.value:
                 if self.category == Category.THREE_TWO.value or self.category == Category.THREE_TWO_LINE.value:
                     self.minor_type = 1
                 self.mode = MODE.MINOR_RESPONSE
                 # modify the state for minor cards
                 discard_onehot_from_s_60(self.prob_state,
                                          Card.val2onehot60(self.intention))
             else:
                 self.finished = True
             return
         elif self.mode == MODE.MINOR_RESPONSE:
             minor_value_cards = [action + 3
                                  ] * (1 if self.minor_type == 0 else 2)
             # modify the state for minor cards
             discard_onehot_from_s_60(self.prob_state,
                                      Card.val2onehot60(minor_value_cards))
             self.intention = np.append(self.intention, minor_value_cards)
             assert self.minor_length > 0
             self.minor_length -= 1
             if self.minor_length == 0:
                 self.finished = True
                 return
             else:
                 return
Esempio n. 42
0
 def createDeck(self):
     deck = []
     for cardName in range(13):
         for cardSuit in range(1,5):
             deck.append(Card(cardName,cardSuit))
     return deck
Esempio n. 43
0
 def build_from_dict(self, dct):
     self.cardId = Card.select_id_by_name(dct['name'])
     return self
Esempio n. 44
0
def _combo_to_hand(combo):
    return [Card.new(combo[:2]), Card.new(combo[2:])]
Esempio n. 45
0
    return indiv_ranges


# TODO: rename to something better descriptive
def _combo_to_hand(combo):
    return [Card.new(combo[:2]), Card.new(combo[2:])]


def card_ints_to_str(cards):
    buildstring = []
    for c in cards:
        buildstring.append(Card.get_str(c))
    return "".join(buildstring)


if __name__ == '__main__':
    print _comboify_hand('KJs')
    print _comboify_hand('KJo')
    print _comboify_hand('66')

    print card_ints_to_str(hand_range_to_cards('random'))

    tt = hand_range_to_cards('TT+')
    for t in card_ints_to_str(tt):
        print t,
    print

    flop = [Card.new('As'), Card.new('Ac'), Card.new('Ad')]
    print card_ints_to_str(hand_range_to_cards('TT+', flop))
Esempio n. 46
0
 def __init__(self):
     self.cards = []  # a list of Card-object
     for number in Card.value_dict:
         for suit in 'sdhc':
             self.cards.append(Card(number, suit))
     random.shuffle(self.cards)
Esempio n. 47
0
 def cards_char2embedding(cards_char):
     test = (action_space_onehot60 == Card.char2onehot60(cards_char))
     test = np.all(test, axis=1)
     target = np.where(test)[0]
     return self.encoding[target[0]]
Esempio n. 48
0
 def __init__(self):
     self._cards = [Card(rank, suit) for suit in Suit for rank in Rank]
Esempio n. 49
0
	def load_deck(self):
		temp = []
		for s in suits:
			for v in values:
				temp.append(Card(s, v))
		return temp
Esempio n. 50
0
 def test_add(self):
     self.fullDeck.add(Card(0))
     self.assertEqual(self.fullDeck.count(), 53)
Esempio n. 51
0
def drop(card_no):

    Card(card_no).drop()

    redirect('/')
Esempio n. 52
0
 def __init__(self):
     self.cards = [Card(suit, rank) for rank, suit in product(Rank, Suit)]
Esempio n. 53
0
 def __init__(self):
     suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
     values = [
         "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"
     ]
     self.cards = [Card(suit, value) for suit in suits for value in values]
Esempio n. 54
0
def make_card(unit):
    return Card(*unit[:3])
Esempio n. 55
0
 def shuffle(self):
     self.__deck = []
     for i in range(52):
         self.__deck.append(Card(i))
     random.shuffle(self.__deck)
Esempio n. 56
0
 def test_peek(self):
     self.assertEqual(self.acesDeck.peek(), Card(51))
     self.assertEqual(self.acesDeck.count(), 4)
Esempio n. 57
0
 def combineDecks(self):
     self.megaDeck = []
     for i in range(4):
         for i in range(4):
             for j in range(0, 14):
                 self.megaDeck.append(Card(i, j))
Esempio n. 58
0
 def __init__(self):
     self.deck = [
         Card(suit, value) for value in Card.values.keys()
         for suit in Card.suits
     ]
Esempio n. 59
0
import sys
sys.path.insert(0,"..")
from game import Game
from player import Player
from card import Card
from test_shoe import TestShoe

class TestPlayer(Player):
    def __init__(self, name="TestPlayer", money=0, default_bet=1):
        super(TestPlayer, self).__init__(name, money)
        self.default_bet = default_bet

    def play(self, dealer, players):
        return "h"

    def bet(self, dealer, players):
        return self.default_bet 

if __name__ == '__main__':

    players = [TestPlayer("test",100)]

    print(players)
    g = Game(players, debug=True, shoe=TestShoe([Card(0,1), Card(0,12), Card(1,1), Card(1,12)] )) 
    g.run()

    print("OVERALL: ", players)
    if str(players) == "[test (100€)]":
        sys.exit(0) 
    sys.exit(1) 
 def setUp(self):
     self.royal_flush_hand = [
         Card('AS'),
         Card('KS'),
         Card('TS'),
         Card('QS'),
         Card('JS')
     ]
     self.straight_flush_hand = [
         Card('9S'),
         Card('KS'),
         Card('TS'),
         Card('QS'),
         Card('JS')
     ]
     self.flush_hand = [
         Card('2C'),
         Card('3C'),
         Card('KC'),
         Card('5C'),
         Card('8C')
     ]
     self.straight_hand = [
         Card('AC'),
         Card('2S'),
         Card('3C'),
         Card('4H'),
         Card('5C')
     ]
     self.full_house_hand = [
         Card('3C'),
         Card('3S'),
         Card('3D'),
         Card('8D'),
         Card('8H')
     ]
     self.four_of_a_kind_hand = [
         Card('4S'),
         Card('4C'),
         Card('4H'),
         Card('4D'),
         Card('JC')
     ]
     self.three_of_a_kind_hand = [
         Card('5D'),
         Card('5H'),
         Card('9S'),
         Card('5C'),
         Card('AS')
     ]
     self.two_pair_hand = [
         Card('5D'),
         Card('5H'),
         Card('9S'),
         Card('9C'),
         Card('AS')
     ]
     self.jacks_or_better_hand = [
         Card('QH'),
         Card('QC'),
         Card('5C'),
         Card('3S'),
         Card('8H')
     ]
     self.non_winning_hand = [
         Card('3D'),
         Card('4C'),
         Card('6C'),
         Card('KC'),
         Card('8H')
     ]