Esempio n. 1
0
	def __HandleNormalCard(self, uid, currentReader):
		if not currentReader.isNewCard(uid):
			Logger.debug("Skipping detected card for reader {}".format(currentReader.id))
			return

		cards = Cards()
		card = cards.getCardFromUID(uid)
		if card is None:
			return

		Logger.debug("Reader {} detected new card: {}".format(currentReader.id, card))

		dataDict = {
			"scope": "READER",
			"command": "card",
			"key": currentReader.id,
			"value": card
		}

		data = json.dumps(dataDict)
		data += "\r\n"
		if not self._connection.send(data):
			Logger.error("Error while sending new card to server")
			self.__Connect()
			# card could not be sent due to connection issues
			currentReader.clearCardFromHold(uid)
Esempio n. 2
0
def create_deck():
    for j in range(0, 4):  # color
        for i in range(7, 15):  # value
            Deck.append(Cards(j, i))
    random.shuffle(Deck)
    for color in range(4):
        winStack.append([Cards(color, 6)])
Esempio n. 3
0
    def test_get_card(self):

        c = Cards()
        c.getCard()

        self.assertNotEqual(c.currDeck, c.FULLDECK)
        self.assertNotEqual(c.deckSize(), len(c.FULLDECK))
Esempio n. 4
0
 def __init__(self):
     # Constructor from inherited Card class
     Cards.__init__(self, suit=0, rank=0)
     self.deck = []  # items stored as example "A of Clubs"
     for suit in self.suits:
         for rank in self.ranks:  # Start at one b/c index 0 holds the dummy value
             self.deck.append(Cards(suit, rank))
Esempio n. 5
0
 def test_aces_hand(self):
     player = Player([Cards("♥", "A"), Cards("♠", "A")], False, 100, 0,
                     True)
     dealer = Dealer([Cards("♦", "A"), Cards("♣", "A")], False, False,
                     False, False)
     self.assertEqual(player.checkSum(), 12, "Player hand should be 12")
     self.assertEqual(dealer.checkSum(), 12, "Dealer hand should be 12")
Esempio n. 6
0
    def combinations(self, n):
	"""Generator function return all combinations of n cards (including
	community cards)."""
	assertInstance(n, int)
	cards = Cards(self)
	if self.board:
	    cards.extend(self.board)
	return Cards.combinations(cards, n)
Esempio n. 7
0
    def test_sum_hand(self):
        player = Player([Cards("♥", "K"), Cards("♠", "10")], False, 100, 0,
                        True)
        dealer = Dealer([Cards("♦", "7"), Cards("♣", "10")], False, False,
                        False, False)

        self.assertEqual(player.checkSum(), 20, "Player hand should be = 20"),
        self.assertEqual(dealer.checkSum(), 17, "Dealer hand should be = 17"),
Esempio n. 8
0
 def SetCardCounter(self):
     cards = Cards()
     card_list = cards.GetCards()
     counter = [
         card for card in card_list
         if card.index not in [x.index for x in self.cards]
     ]
     self.CardCounter.SetCardData(counter)
     self.CardCounter.ParseHandCardData()
Esempio n. 9
0
 def test_changecards_7(self):
     playerAux = Players("Pepe", 35, "orange", [])
     card1 = Chivalry()
     card2 = Cards()
     card3 = Cards()
     cards = [card1, card2, card3]
     expected = 0
     playerAux.addcards(cards)
     cardsleft = playerAux.changecards()
     self.assertEqual(expected, cardsleft)
Esempio n. 10
0
 def test_sixcardsok(self):
     cards = [
         Cards(),
         Infantry(),
         Chivalry(),
         Artillery(),
         Cards(),
         Infantry()
     ]
     player = IAPlayers("Pepe", 0, "orange", cards)
     expected = False
     self.assertEqual(expected, GameRules.checkcardsnum(player))
Esempio n. 11
0
class Table(object):
    def __init__(self, number_of_decks, number_of_players, name_of_players):
        self.dealer = Dealer()
        self.players = [Player(name) for name in name_of_players]
        self.cards = Cards(number_of_decks)

    def distribute_card_to_dealer(self):
        self.dealer.hand.append(self.cards.take_a_card_from_stack())

    def distribute_card_to_player(self, player):
        player.hand.append(self.cards.take_a_card_from_stack())

    def show_first_card_of_dealer(self):
        return {self.dealer.name: self.dealer.hand[0]}

    def show_cards_of_players(self):
        return {player.name: player.hand for player in self.players}

    def calc_score(self, player_or_dealer):
        player_or_dealer.score = 0
        player_or_dealer.value_for_ace_card = 11
        for card_key, card_value in player_or_dealer.hand:
            if card_key == 'A':
                player_or_dealer.score += player_or_dealer.value_for_ace_card
            else:
                player_or_dealer.score += card_value
        if player_or_dealer.score > 21 and ('A',
                                            None) in player_or_dealer.hand:
            player_or_dealer.score -= 10
            player_or_dealer.value_for_ace_card = 1
        return player_or_dealer.score

    def get_the_results_of_game(self):
        results = []
        for player in self.players:
            if self.dealer.score > 21 and player.score <= 21:
                results.append({'dealer': 'Loser', player.name: 'Winner'})
            elif (player.score > 21) or (21 > self.dealer.score >
                                         player.score):
                results.append({'dealer': 'Winner', player.name: 'Loser'})
            elif self.dealer.score < 21 and self.dealer.score < player.score:
                results.append({'dealer': 'Loser', player.name: 'Winner'})
            elif self.dealer.score == player.score == 21 and \
                    len(self.dealer.hand) == 2 and len(player.hand) > 2:
                results.append({'dealer': 'Winner', player.name: 'Loser'})
            elif self.dealer.score == player.score == 21 \
                    and len(self.dealer.hand) > 2 and len(player.hand) == 2:
                results.append({'dealer': 'Loser', player.name: 'Winner'})
            elif (self.dealer.score == player.score == 21 and
                  len(self.dealer.hand) == 2 and len(player.hand) == 2) \
                    or (self.dealer.score == player.score):
                results.append({'dealer': 'Push', player.name: 'Push'})
        return results
Esempio n. 12
0
    def __init__(self, row_size = 50):
        self.cards = Cards()
        x = np.random.normal(37, 5, size=1)
        print("End sampled from normal distribution with mu=37 and sigma=5")
        self.end = min(int(x[0]), 51)

        pygame.display.set_caption('Kings Cup')
        self.window = pygame.display.set_mode((700, 700))

        self.rules = {1: 'Waterfall', 2: 'You', 3: 'Me', 4: 'Floor (point)', 5: 'Guys',
                        6: 'Chicks', 7: 'Heaven', 8: 'Mate', 9: 'Rhyme',
                        10: 'Categories', 11: 'Never Have I ever', 12: 'Questions',
                        13: 'Make a Rule'}
Esempio n. 13
0
 def test_threechivalryexchange(self):
     cards = [
         Cards(),
         Infantry(),
         Chivalry(),
         Artillery(),
         Cards(),
         Infantry()
     ]
     player = IAPlayers("Pepe", 0, "orange", cards)
     expected = True
     self.assertEqual(expected,
                      GameRules.cardstoexchangeok(player, "chivalry"))
Esempio n. 14
0
 def has_ip(self, sock):
     resp = sock.recv(400)
     sock.close()
     try:
         ip = resp.split('ip=')[1].split('\n')[0]
         essid = resp.split('essid=')[1].split('\n')[0]
         if is_ip(ip):
             if self.only and ip != self.only:
                 raise socket.timeout
             cards = Cards()
             new_card = Card(ip, essid)
             if new_card not in cards:
                 cards.add(new_card)
                 new_card.start()
     except IndexError:
         pass
Esempio n. 15
0
    def __init__(self) :
        for i in range (1,53) :
            newcard = Cards(i)
            self.newlist.append(newcard)

        random.shuffle(self.newlist)
        DeckOfCards.availablecards = 52
Esempio n. 16
0
    def __init__(self):
        self.deck = []

        for suit in suits:
            for rank in ranks:
                self.new_card = Cards(suit, rank)
                self.deck.append(self.new_card)
Esempio n. 17
0
def generateAllShowdownsFor2Players(lock,
                                    counter,
                                    previousPercentage,
                                    initial_time,
                                    verbose=True):
    hero = Player(name="Hero", positionAtTable=0, stack=1000)
    villain = Player(name="Villain", positionAtTable=1, stack=1000)
    table = Table(players=[hero, villain], bigBlind=100)
    table.game.gameRound = GameRound.END
    # probabilities = {heroHand: {villainHand: {board: 0 for board in combinations(table.game.deck, 5)} for villainHand in combinations(table.game.deck, 2)} for heroHand in combinations(table.game.deck, 2)}
    # probabilities = {}

    while counter.value < numberOfCombinations:
        cards = next(
            showdownCombinations)  # TODO - HOW TO PROCESS LOCK? CHECK POINTS!
        counter.value += 1

        hero.setHandIgnoringDiscard(*cards[:2])
        villain.setHandIgnoringDiscard(*(cards[2:4]))
        table.board.setCardsIgnoringDiscard(*(cards[4:9]))

        heroPoint = hero.getBestFiveCards().point
        villainPoint = hero.getBestFiveCards().point
        if heroPoint == villainPoint:
            win, tie, lose = 0, 1, 0
        elif heroPoint > villainPoint:
            win, tie, lose = 1, 0, 0
        else:
            win, tie, lose = 0, 0, 1

        toChunks(
            lock, '{};{};{};{};{};{}'.format(str(hero.hand), str(villain.hand),
                                             Cards(*table.board), win, tie,
                                             lose))

        # if hero.hand not in probabilities:
        #     probabilities[hero.hand] = {}
        # if villain.hand not in probabilities[hero.hand]:
        #     probabilities[hero.hand][villain.hand] = {}
        # if board not in probabilities[hero.hand][villain.hand]:
        #     probabilities[hero.hand][villain.hand][board] = 0

        if verbose:
            percentage = round(counter.value / numberOfCombinations, 6)
            # if percentage > previousPercentage.value:
            #     previousPercentage.value = percentage
            #     print("{:.2f} - {:.4f}%".format(time() - initial_time.value, percentage * 100))
            if percentage >= 0.00001:  # EXIT
                lock.acquire()
                with open('CSV/Showdowns.csv', 'a+', encoding='utf-8') as sd:
                    sd.write('\n')
                    sd.write('\n'.join(chunks))
                lock.release()
                return

    lock.acquire()
    with open('CSV/Showdowns.csv', 'a+', encoding='utf-8') as f:
        f.write('\n'.join(chunks))
    lock.release()
Esempio n. 18
0
 def __str__(self):
     if self.name != "":
         representation = self.name
     else:
         representation = "Player #" + str(self.positionAtTable + 1)
     if self.hand is not None:
         representation += " - " + str(Cards(*self.hand))
     return representation
Esempio n. 19
0
    def test__cards(self):

        # Test for add
        card = Cards.add(merchant_id='shreyas', customer_id="user", customer_email='*****@*****.**',
                                card_number=str(int(self.timestamp)*(10**6)), card_exp_year='20', card_exp_month='12')
        self.assertIsNotNone(card.reference)
        self.assertIsNotNone(card.token)
        self.assertIsNotNone(card.fingerprint)
        #print tab(var_dump(card))

        # Test for delete
        deleted_card = Cards.delete(card_token=card.token)
        self.assertTrue(deleted_card.deleted)
        #print tab(var_dump(deleted_card))

        # Test for list
        Test.delete_all_cards()
        Cards.add(merchant_id='shreyas', customer_id="user", customer_email='*****@*****.**',
                         card_number=str(int(self.timestamp) * (10 ** 6)), card_exp_year='20', card_exp_month='12')
        Cards.add(merchant_id='shreyas', customer_id="user", customer_email='*****@*****.**',
                         card_number=str((int(self.timestamp)+1) * (10 ** 6)), card_exp_year='20', card_exp_month='12')
        card_list = Cards.list(customer_id='user')
        self.assertIsNotNone(card_list)
        self.assertEqual(len(card_list), 2)
        #print tab(var_dump(card_list))
        Test.delete_all_cards()
Esempio n. 20
0
 def __init__(self):
     """
     initialize the players and set default parameters
     """
     playerAcards, playerBcards = Cards().generateSets()
     self.playerA = Player(playerAcards)
     self.playerB = Player(playerBcards)
     self.numDrawCards = self.playerA.numDrawCards
     self.numMapping = {11: "Jack", 12: "Queen", 13: "King", 14: "Ace"}
Esempio n. 21
0
    def __init__(self):
        """
        Initializes a deck in order
        """

        self.cards = []
        for face in Deck.faces:
            for suit in Deck.suits:
                self.cards.append(Cards(suit, face))
Esempio n. 22
0
    def GameStart(self):
        cards = Cards()
        card_group, landlord_cards = cards.DealPoker()
        for i, player in enumerate(self.players):
            player.SetCardList(card_group[i])
            player.WriteHandCardList()
        print(
            "===========================landlord_cards=======================")
        ShowCard(landlord_cards)
        self.game_status = 1
        self.game_score = 0
        while self.game_status == 1:
            if self.landlord.CallLandlord(self.game_score):
                self.game_score = self.landlord.GetCallScore()
                self.landlord.AddBottomCardList(landlord_cards)
                self.game_status = 2
            self.landlord = self.landlord.GetNextPlayer()

        print(self.landlord.GetDeskStation())
Esempio n. 23
0
	def addcards(self,newCards):
		for card in newCards:
			if card.getname() == "infantry":
				self.__CARDS.append(Infantry())
			elif card.getname() == "chivalry":
				self.__CARDS.append(Chivalry())
			elif card.getname() == "artillery":
				self.__CARDS.append(Artillery())
			elif card.getname() == "joker":
				self.__CARDS.append(Cards())
		return self.getcardsnumber()
Esempio n. 24
0
	def picacard(self):
		type = randint(1,4)
		if type == 1:
			self.__CARDS.append(Cards())
		elif type == 2:
			self.__CARDS.append(Infantry())
		if type == 3:
			self.__CARDS.append(Chivalry())
		if type == 4:
			self.__CARDS.append(Artillery())
		return self.getcardsnumber()
Esempio n. 25
0
    def test_full_deck(self):

        c = Cards()

        self.assertEqual(c.FULLDECK, [
            '2 of spades', '2 of clubs', '2 of diamonds', '2 of hearts',
            '3 of spades', '3 of clubs', '3 of diamonds', '3 of hearts',
            '4 of spades', '4 of clubs', '4 of diamonds', '4 of hearts',
            '5 of spades', '5 of clubs', '5 of diamonds', '5 of hearts',
            '6 of spades', '6 of clubs', '6 of diamonds', '6 of hearts',
            '7 of spades', '7 of clubs', '7 of diamonds', '7 of hearts',
            '8 of spades', '8 of clubs', '8 of diamonds', '8 of hearts',
            '9 of spades', '9 of clubs', '9 of diamonds', '9 of hearts',
            '10 of spades', '10 of clubs', '10 of diamonds', '10 of hearts',
            'J of spades', 'J of clubs', 'J of diamonds', 'J of hearts',
            'Q of spades', 'Q of clubs', 'Q of diamonds', 'Q of hearts',
            'K of spades', 'K of clubs', 'K of diamonds', 'K of hearts',
            'A of spades', 'A of clubs', 'A of diamonds', 'A of hearts'
        ] * c.getNumDecks())
        self.assertEqual(c.FULLDECK, c.currDeck)
        self.assertEqual(c.deckSize(), len(c.FULLDECK))
Esempio n. 26
0
 def test_delcards(self):
     cards = [
         Infantry(),
         Artillery(),
         Infantry(),
         Cards(),
         Infantry(),
         Chivalry()
     ]
     playerAux = IAPlayers("Pepe", 35, "orange", cards)
     expected = 3
     self.assertEqual(expected, playerAux.delcards("infantry", 3))
Esempio n. 27
0
    def test_shuffle(self):

        c = Cards()
        c.getCard()
        c.shuffle()

        self.assertEqual(c.currDeck, c.FULLDECK)
Esempio n. 28
0
    def __init__(self, model):
        #Initialize a deck of cards
        self.cards = Cards()

        #import related parameters
        self.end = False
        self.last_move_type = self.last_move = "start"
        self.playround = 1
        self.i = 0
        self.Pass = []

        #choose model
        self.model = model
Esempio n. 29
0
File: Hand.py Progetto: von/pyPoker
    def combinations_of_eight_or_lower(self, n):
        """Generator function returns all combinations (including community
        cards) of n cards that are 8 or lower (including aces).

        If there aren't n cards 8 or lower, return noths."""
        cards = self.getEightOrLower()
        if self.board:
            cards.extend(self.board.getEightOrLower())
        cards = cards.removeDuplicateRanks()
        # Do not fail if we don't have enough cards 8 or lower
        if len(cards) < n:
            return iter([])
        return Cards.combinations(cards, n)
Esempio n. 30
0
    def createDeck(self):
        deckValues = [
            'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'
        ]
        deckSuits = ['♥', '♠', '♦', '♣']

        # Make 1 of each card
        for suit in deckSuits:
            for number in deckValues:
                self.deck.append(Cards(suit, number))

        # Shuffle to randomize the deck
        random.shuffle(self.deck)
        return self.deck
Esempio n. 31
0
    def initdeck(self):
        n = 1
        while n < 53:
            Tempnum = random.randint(1, 13)
            Temptype = random.randint(0, 3)
            Temp = Cards(Tempnum, self.types[Temptype])
            Existence = False
            i = 0
            while i < len(self.Rawdeck):
                if self.Rawdeck[i].getnumber() is Tempnum and self.Rawdeck[
                        i].gettype() is self.types[Temptype]:
                    Existence = True
                i = i + 1

            if Existence == False:
                self.Rawdeck.append(Temp)
            n = n + 1
Esempio n. 32
0
    def OnOpen(self, e):
        wildcard = "Text File (*.txt)|*.txt"
        dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "",
                               wildcard, wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            path = dialog.GetPath()
        else:
            sys.exit("No text file selected")
        dialog.Destroy()

        newCards = getNotes(path)
        # destroy all the card buttons in the left panel
        for i in range(0, len(self.splitter.cards.JSON)):
            button = self.FindWindowByName(str(i))
            button.Destroy()
        # set the new cards, create buttons for the left panel, update the card for the right panel
        self.splitter.cards = Cards(newCards)
        LeftPanel.createButtons(self.splitter.leftP, self.splitter, self)
        RightPanel.updateText(self.splitter.rightP, self.splitter.cards)
        self.splitter.leftP.SetupScrolling()
Esempio n. 33
0
	def delcards(self,nameCard,num):
		#borra cartas de UN TIPO. Tantas llamadas como tipo de cartas
		[jokCount,infCount,chiCount,artCount] = self.getcardtypenumber()
		if nameCard == "infantry":
			infCount = infCount - num
		elif nameCard == "chivalry":
			chiCount = chiCount - num
		elif nameCard == "artillery":
			artCount = artCount - num
		elif nameCard == "joker":
			jokCount = jokCount - num

		self.__CARDS = [] #vaciamos la lista
		for i in range(1,infCount+1):
			self.__CARDS.append(Infantry())
		for i in range(1,chiCount+1):
			self.__CARDS.append(Chivalry())
		for i in range(1,artCount+1):
			self.__CARDS.append(Artillery())
		for i in range(1,jokCount+1):
			self.__CARDS.append(Cards())
		return self.getcardsnumber()
Esempio n. 34
0
    def getHoleCards(self):
	"""Return the hole (non-community) cards."""
	c = Cards()
	c.extend(self)
	return c
Esempio n. 35
0
 def delete_all_cards():
     card_list = Cards.list(customer_id='user')
     for card in card_list:
         Cards.delete(card_token=card.token)
Esempio n. 36
0
    def getUpCards(self):
	cards = Cards()
	for card in range(len(self)):
	    if self.isUpCard(card):
		cards.append(self[card])
	return cards
Esempio n. 37
0
    def append(self, card):
	"""Append while checking to be sure maxCards is not exceeded."""
	if self.maxCards and (len(self) == self.maxCards):
	    raise TooManyCardsException()
	assertInstance(card, Card)
	Cards.append(self, card)
Esempio n. 38
0
    def hands(self):
	"""Return all sets of cards that can be constructed from hand."""
	cards = Cards(self)
	if self.board:
	    cards.extend(self.board)
	yield cards
Esempio n. 39
0
    def __str__(self):
	string = Cards.__str__(self)
	for card in range(self.maxCards - len(self)):
	    string += " xx"
	return string.strip()
Esempio n. 40
0
    def extend(self, cards):
	"""Extend while checking to be sure maxCards is not exceeded."""
	if self.maxCards:
	    if len(self) + len(cards) > self.maxCards:
		raise TooManyCardsException()
	Cards.extend(self, cards)