def __init__(self): self.players = list() self.dealer = BjPlayer(-1) self.deck = Deck(6) self.current_turn_player_id = 0 self.current_phase = BjPhases.END self._player_counter = 0
def testaddCard(self): testdeck = Deck() card = Card(1,"As") testdeck.addCard(card) self.assertEqual(testdeck.__repr__(), "[A Card]") card = Card(2,"Deux") testdeck.addCard(card,False) self.assertEqual(testdeck.__repr__(), "[{'name': 'Deux', 'value': 2, 'description': None}, A Card]") card = Card(3,"Trois") testdeck.addCard(card,False,2) self.assertEqual(testdeck.__repr__(), "[{'name': 'Deux', 'value': 2, 'description': None}, {'name': 'Trois', 'value': 3, 'description': None}, A Card]")
def __init__(self, players): ''' Constructor ''' threading.Thread.__init__(self, name = self.__class__.__name__) logging.info( "Thread " + str(self.__class__.__name__) + " created") self._players = players loaderName=configuration.config.get("Modules", "deck.loader") logging.info("Importing deck loader " + loaderName) loader=importlib.import_module(loaderName) deck = Deck() deck.data = loader.createDeck(configuration.config.get("Files","deck.filename")) deck.shuffle() self._decks["Main"] = deck self._decks["Graveyard"] = Deck("Graveyard")
class TestHand(TestCase): def setUp(self): self.deck = Deck() self.deck.populate() self.hand = Hand(player=Player('Fred'), from_deck=self.deck) def test_hand_draw(self): self.hand.draw() self.assertEqual(len(self.hand), 1) def test_hand_discard(self): card = self.hand.draw() self.hand.discard(card) self.assertEqual(len(self.hand), 0) def test_hand_value(self): card1 = self.hand.draw() card2 = self.hand.draw() self.assertEqual(self.hand.value(), card1.value + card2.value)
class Test(unittest.TestCase): def setUp(self): self.deck = Deck() self.deck.data = fileloader.createDeck() def tearDown(self): pass def testShuffle(self): initdeck=copy.deepcopy(self.deck) self.deck.shuffle() self.assertNotEqual(self.deck, initdeck) def testdraw(self): numberOfCards = len(self.deck) self.deck.draw() self.assertEqual(len(self.deck), numberOfCards - 1) numberOfCards = numberOfCards - 1 self.deck.draw(5) self.assertEqual(len(self.deck), numberOfCards - 5) def testaddCard(self): testdeck = Deck() card = Card(1,"As") testdeck.addCard(card) self.assertEqual(testdeck.__repr__(), "[A Card]") card = Card(2,"Deux") testdeck.addCard(card,False) self.assertEqual(testdeck.__repr__(), "[{'name': 'Deux', 'value': 2, 'description': None}, A Card]") card = Card(3,"Trois") testdeck.addCard(card,False,2) self.assertEqual(testdeck.__repr__(), "[{'name': 'Deux', 'value': 2, 'description': None}, {'name': 'Trois', 'value': 3, 'description': None}, A Card]") def testshowCard(self): self.assertEqual(self.deck.getCard(), "{'color': 'Coeur', 'name': 'As', 'value': '1'}") self.assertEqual(self.deck.getCard(7), "{'color': 'Coeur', 'name': 'Sept', 'value': '7'}")
def setUp(self): self.deck = Deck() self.deck.data = fileloader.createDeck()
def unserialize(data): logging.debug("unserialize " + str(data)) data = data["data"] data["hand"] = Deck.unserialize(data["hand"]) return Player(attributes=data)
def setUp(self): self.instance = Deck()
class TestDeck(TestCase): def setUp(self): self.instance = Deck() def test_deck_length(self): """Make sure the deck is 52 cards""" assert(len(self.instance) == 52) def test_card_rank(self): """Make sure rank is valid""" card = self.instance.dealone(to_location='discard') assert(card.rank in RANKS) def test_card_suit(self): """Make sure the suit is valid""" card = self.instance.dealone(to_location='discard') assert(card.suit in SUITS) def test_card_value(self): """Make sure the value is applied to the card""" card = Card(rank='king', suit='spades', value=42) self.assertEqual(card.value, 42) def test_card_comparator_lt(self): """Does __lt__ work as expected?""" card1 = Card('two', 'hearts', 2) card2 = Card('three', 'spades', 3) assert card1 < card2 def test_card_comparator_gt(self): """Does __gt__ work as expected""" card1 = Card('two', 'hearts', value=11) card2 = Card('two', 'hearts', value=12) self.assertGreater(card2, card1) def tests_card_operator_ne(self): """Does __ne__ work as expected?""" card1 = Card('two', 'hearts', value=11) card2 = Card('two', 'hearts', value=12) self.assertTrue(card2 != card1) def test_deck_repr(self): """Repr should return a descriptive string""" card = Card('two', 'hearts', value=2) self.assertEqual('two of hearts', card.__repr__()) def test_deck_setitem(self): """Can we insert cards into the deck?""" card = Card('ace', 'fudgeos', 10) self.instance[3] = card self.assertIn(Card('ace', 'fudgeos', 10), self.instance) def test_dealone(self): """Make sure deck is reduced by one when we deal a card""" l1 = len(self.instance) self.instance.dealone('discard') l2 = len(self.instance) assert(l1 - l2 == 1) def test_shuffle(self): """Make sure the deck is shuffled properly""" self.instance.shuffle() unshuffled = Deck() # testing that at least one card differs. Dumb, but how else to check # so that the test doesn't fail randomly? assert(not all([self.instance[i] == unshuffled[i] for i in range(52)])) def test_no_shuffle(self): """Make sure the first card in an unshuffled deck is the king of clubs""" assert(self.instance.dealone('discard') == Card('king', 'clubs', 10)) def test_deal_no_shuffle(self): """Make sure deal works as expected""" kc = Card('king', 'clubs', 10) kd = Card('king', 'diamonds', 10) ks = Card('king', 'spades', 10) kh = Card('king', 'hearts', 10) expected = {'a': [kc, kd], 'b': [ks, kh]} actual = self.instance.deal(players=['a', 'b'], cardcount=2) assert(actual == expected) def test_deal_length_change(self): """Deal should reduce the deck length by cardcount parameter""" self.instance.deal(['a', 'b'], 2) assert(len(self.instance) == 48) def test_bad_cardcount_value(self): """Raise ValueError if cardcount*players is larger than deck length""" self.assertRaises(ValueError, self.instance.deal, ['a', 'b'], 27) def test_non_card_raises_type_error(self): """Raise TypeError if the 'cards' argument to populate contains non-cards""" deck = Deck() cards = [Card('king', 'spades'), Card( 'king', 'diamonds'), Card('ace', 'hearts'), 8] self.assertRaises(TypeError, deck.populate, cards) def test_some_values(self): """Check some card values""" self.instance.shuffle() for p in self.instance: if p.rank == 'ace': assert(p.value == 1) if p.rank == 'ten': assert(p.value == 10) if p.rank == 'jack': assert(p.value == 10)
def setUp(self): self.deck = Deck() self.deck.populate() self.hand = Hand(player=Player('Fred'), from_deck=self.deck)
class BjGameState: def __init__(self): self.players = list() self.dealer = BjPlayer(-1) self.deck = Deck(6) self.current_turn_player_id = 0 self.current_phase = BjPhases.END self._player_counter = 0 def update(self, player_update): apply_fn = { BjPlayerActions.STAND: BjGameState._apply_stand, BjPlayerActions.HIT: BjGameState._apply_hit, BjPlayerActions.DOUBLE: BjGameState._apply_double, BjPlayerActions.SPLIT: BjGameState._apply_split, BjPlayerActions.SURRENDER: BjGameState._apply_surrender, BjPlayerActions.INSURANCE: BjGameState._apply_insurance, BjPlayerActions.BET: BjGameState._apply_bet, BjPlayerActions.JOIN: BjGameState._apply_join } if player_update.action not in apply_fn: raise (BjGameError('unknown action {}'.format( player_update.action))) if player_update.action != BjPlayerActions.JOIN and player_update.player_id != self.current_turn_player_id: raise (BjGameError('it is not this players turn')) if player_update.hand_idx is None and player_update.action not in [ BjPlayerActions.JOIN, BjPlayerActions.INSURANCE ]: raise (BjGameError('missing required hand_id for this action')) new_state = copy.deepcopy(self) apply_fn[player_update.action](new_state, player_update) return new_state def _apply_stand(self, player_update): self._end_turn() def _apply_hit(self, player_update): (p, h) = self._get_player_and_hand(player_update) h.cards.append(self.deck.deal(1)[0]) if h.score() > 21: self._end_turn() def _apply_double(self, player_update): pass def _apply_split(self, player_update): pass def _apply_surrender(self, player_update): pass def _apply_insurance(self, player_update): pass def _apply_bet(self, player_update): if self.current_phase == BjPhases.END: self._start_round() elif self.current_phase != BjPhases.BET: raise (BjGameError('cannot bet outside of the bet phase')) (p, h) = self._get_player_and_hand(player_update) if p.total_credit < player_update.bet_amt: raise (BjGameError('insufficient funds to place bet')) p.total_credit -= player_update.bet_amt h.bet_amt += player_update.bet_amt self._end_turn() def _apply_join(self, player_update): if self.current_phase not in [BjPhases.BET, BjPhases.END]: raise (BjGameError( 'cannot join the game outside of the bet or end phase')) self._player_counter += 1 if len(self.players) == 0: self.current_turn_player_id = self._player_counter self.players.append( BjPlayer(self._player_counter, player_update.bet_amt)) def _get_player_and_hand(self, player_update): for p in self.players: if p.id == player_update.player_id: if len(p.hands) > player_update.hand_idx >= 0: return (p, p.hands[player_update.hand_idx]) def _start_round(self): self.current_phase = BjPhases.BET for p in self.players: p.insurance_bet = 0 p.hands.clear() p.hands.append(BjHand()) self.dealer.hands.clear() self.dealer.hands.append(BjHand()) def _end_turn(self): try: next_player = next( filter(lambda p: p.id > self.current_turn_player_id, self.players)) self.current_turn_player_id = next_player.id except StopIteration: # Getting here means all other players have played and its the dealer's turn if self.current_phase == BjPhases.BET: self._deal_players() if self.dealer.hands[0].cards[0].face == 'A': self.current_phase = BjPhases.INSURANCE else: self.current_phase = BjPhases.PLAY elif self.current_phase == BjPhases.PLAY: self._dealer_play() self._end_round() elif self.current_phase == BjPhases.INSURANCE: if self.dealer.hands[0].is_blackjack(): self._end_round() else: self.current_phase = BjPhases.PLAY self.current_turn_player_id = min([p.id for p in self.players]) def _dealer_play(self): dealer_hand = self.dealer.hands[0] score = dealer_hand.score() while score < 17: dealer_hand.cards.append(self.deck.deal(1)[0]) score = dealer_hand.score() def _end_round(self): self.current_phase = BjPhases.END dealer_hand = self.dealer.hands[0] dealer_score = dealer_hand.score() dealer_blackjack = dealer_hand.is_blackjack() for p in self.players: for h in p.hands: payout = 0 hand_score = h.score() hand_blackjack = h.is_blackjack() h.outcome = BjHandOutcomes.LOST if hand_score <= 21: if hand_score > dealer_score: h.outcome = BjHandOutcomes.WON if hand_blackjack: payout = math.ceil(h.bet_amt * 5 / 2) else: payout = h.bet_amt * 2 elif hand_score == dealer_score: if dealer_blackjack == hand_blackjack: h.outcome = BjHandOutcomes.PUSH payout = h.bet_amt elif dealer_score > 21: h.outcome = BjHandOutcomes.WON payout = h.bet_amt * 2 p.total_credit += payout if dealer_blackjack and p.insurance_bet > 0: p.total_credit += p.insurance_bet * 2 def _deal_players(self): for p in self.players: p.hands[0].cards = self.deck.deal(2) self.dealer.hands[0].cards = self.deck.deal(2)