Exemplo n.º 1
0
 def trow_away_card(self):
     '''Trow away a card, if you can't confess a card'''
     self.pp("We want to trow away a card")
     colors = self.cards.colors()
     if self.trump in colors:
         colors.remove(self.trump)
     if len(colors) == 1:
         self.pp(
             "Trow away the lowest card we have of the only possible color")
         return sorted(self.cards.filter_color(colors[0]))[0]
     if len(colors) == 0:
         raise NotImplementedError(
             "We only have trumps, shouldn't call this function")
     poss = Cards()
     for color in colors:
         filt = self.cards.filter_color(color)
         if len(filt) >= 4:
             self.pp(
                 "We trow away the lowest card of the color we have the most of"
             )
             return sorted(filt)[0]
         if filt.has(TEN) and not self.is_high(filt.has(TEN)): continue
         filt = filt.filter(lambda c: c.value not in (TEN, ACE))
         poss.extend(filt)
     if poss:
         self.pp(
             "Trowing away a low card in a colour that doesn't have a low TEN"
         )
         return sorted(poss)[0]
     self.pp(
         "We have a Ten in every playable color. Play a card in one of them"
     )
     return sorted(self.cards.filter(self.is_not_trump))[0]
Exemplo n.º 2
0
	def publish(self):
		self.context.dice = Dice()
		self.context.chest = Cards(communityChestCards)
		self.context.chance = Cards(chanceCards)
		if self.context.INITIAL_STATE == "DEFAULT":
			self.context.state =  State(self.PLAY_ORDER)
		elif self.context.INITIAL_STATE == "TEST_BUY_HOUSES":
			properties = [Property(0,False,False,0,i) for i in range(NUMBER_OF_PROPERTIES)]
			agentOne = self.PLAY_ORDER[0]
			properties[6].owned = True
			properties[6].ownerId = agentOne
			properties[8].owned = True
			properties[8].ownerId = agentOne
			properties[9].owned = True
			properties[9].ownerId = agentOne
			agentTwo = self.PLAY_ORDER[1]
			properties[11].owned = True
			properties[11].ownerId = agentTwo
			properties[13].owned = True
			properties[13].ownerId = agentTwo
			properties[14].owned = True
			properties[14].ownerId = agentTwo
			self.context.state = State(self.PLAY_ORDER,properties)
		self.context.winner = None
			
		log("game","Game #"+str(self.context.gamesCompleted+1)+" started.")
		
		#Allow the agent to initialize state for a new game
		self.agentsYetToRespond = list(self.PLAY_ORDER)
		self.publishAction(None,"START_GAME_IN")
Exemplo n.º 3
0
 def legal_cards(self, played_cards):
     if not played_cards: return self.cards #first to play, everything is legal
     played_cards = Cards(played_cards)
     color = played_cards[0].color
     played_trumps = played_cards.filter_color(self.trump)
     highest = highest_card(played_cards)
     if highest.owner == None:
         raise KeyError("Played card doesn't have owner")
     winning = (highest.owner == self.partner)
     cards = self.cards.filter_color(color)
     if cards: #we can confess colour
         if color != self.trump: return cards #no trumps so no restrictions
         #must not undertrump
         higher = [t for t in cards if t>highest]
         if higher: return higher # We must overtrump
         return cards
     trumps = self.cards.get_trumps()
     if not trumps: return self.cards # Don't have any trumps so everything is legal
     if not played_trumps and not winning: return trumps # We aren't winning and we have trumps, so we must play one of those
     higher = [t for t in trumps if t>highest]
     if higher and not winning: return higher # We must overtrump
     c = self.cards.filter(lambda c: c.color!=self.trump) #Any card except trumps
     c.extend(higher)
     if c: return c
     return self.cards #we can't overtrump, but we only have trumps so we need to play them.
Exemplo n.º 4
0
def publish(context):
	#reinitialize state for the new game
	context.winner = None
	context.dice = Dice()
	context.chest = Cards(communityChestCards)
	context.chance = Cards(chanceCards)
	
	if context.INITIAL_STATE == "DEFAULT":
		context.state =  State(context.PLAY_ORDER)
	elif context.INITIAL_STATE == "TEST_BUY_HOUSES":
		properties = [Property(0,False,False,0,i) for i in range(NUMBER_OF_PROPERTIES)]
		agentOne = context.PLAY_ORDER[0]
		properties[6].ownerId = agentOne
		properties[8].ownerId = agentOne
		properties[9].ownerId = agentOne
		agentTwo = context.PLAY_ORDER[1]
		properties[11].ownerId = agentTwo
		properties[13].ownerId = agentTwo
		properties[14].ownerId = agentTwo
		context.state = State(context.PLAY_ORDER,properties)
		
	log("game","Game #"+str(context.gamesCompleted+1)+" started.")
	
	# all the agents provided can access the startGame API
	return context.PLAY_ORDER
Exemplo n.º 5
0
    def select_subject_category(self):
        pass
        # ask of what subject and catagory to compile cards for.
        study_card = Cards()
        subject_select = ''
        cat_select = ''
        subject_list = study_card.display_subject_list('mainsubject')
        print(f'Subject list: {subject_list}\n')
        subject = input('Please select which Subject to review: ')
        if subject.lower() == 'q':
            print('Good Bye')
            return exit()
        for i in subject_list:
            if i != subject.lower():
                pass
            else:
                subject_select = i
                print("\nSubject Selected: " + subject_select + '\n')

        cat_list = study_card.display_subject_list(subject_select, 'category')
        print(f'Category: {cat_list}\n')
        category = input('Please select which category to review: ')
        if category.lower() == 'q':
            print('Good Bye')
            return exit()
        for i in cat_list:
            if i != category.lower():
                pass
            else:
                cat_select = i
                print("\nCategory Selected: " + cat_select + '\n')

        return (subject_select, cat_select)
Exemplo n.º 6
0
    def test_sub(self):
        cards = [Card(name='2', suit='Pagoda'), Card(name='2', suit='Sword')]
        cards = Cards(cards_list=cards)

        cards_to_remove = Cards(cards_list=[Card(name='2', suit='Sword')])

        cards = cards - cards_to_remove
        self.assertEqual(cards.size, 1)
Exemplo n.º 7
0
 def __init__(self):
     self.name = 'mongoaudit'
     self.version = __version__
     check_version(self.version)
     urwid.set_encoding("UTF-8")
     self.cards = Cards(self)
     self.setup_view()
     self.main()
Exemplo n.º 8
0
    def _evaluate_move(self, this: int, cards: Cards, history: Set[int],
                       depth: int) -> Tuple[int, int, int, int]:
        """
        Like next_move, but it also returns a result, which says what 
        the final best-case result is as a result of this move.

        Returns a tuple of (other_player, suit, result, draw_position)
        """
        permutation = cards.permutation(this)

        # just for now, override the cache
        # return self._evaluate_move_uncached(this, cards, history, depth, permutation)

        # see whether this move is in the cache
        pos = cards.position_given_permutation(permutation, this)
        n = len(permutation)
        if pos in self._cached_moves:
            other_c, suit_c, result_c = self._cached_moves[pos]
            other = (other_c + this) % n
            result = result_c if result_c < 0 else (result_c + this) % n
            suit = int(permutation[suit_c])

            # Just for debugging, check that the non-cached result is the same
            # Note that because of the way we check for repeats by looking in
            # the history, it is possible that a draw may be possible via more
            # than one route, and different drawing moves may result from
            # different histories. We therefore do not worry if the moves are
            # different but both result in a draw.
            # other_u, suit_u, result_u = self._evaluate_move_uncached(this, cards, history, depth, permutation)
            # if result == -1 and result_u == -1:
            #     pass    # don't worry about the moves if both result in a draw
            # elif other_u != other or suit_u != suit or result_u != result:
            #     print(f"cache fail ({pos}): cards={cards} cached=({other_c}, {suit_c}, {result_c}) => ({other}, {suit}, {result}) uncached={other_u, suit_u, result_u} this={this} perm={permutation}")

            # Always return -1 as the draw position of any cached move. Since
            # the position was cached, we know that it is a genuine forcing draw,
            # so any position will do, so long as it is not in the history. We
            # know that -1 is not a valid position
            return other, suit, result, -1

        # find the best move and cache it
        other, suit, result, draw_position = self._evaluate_move_uncached(
            this, cards, history, depth, permutation)
        other_c = (other - this) % n
        result_c = result if result < 0 else (result - this) % n
        found = np.where(permutation == suit)
        assert len(found) == 1 and len(found[0]) == 1
        suit_c = int(found[0][0])

        # Only save winning positions to the cache, as draws may only be a draw given
        # the current history, rather than being indicative of a draw in general. However,
        # if this is a draw and the position that caused the draw is not in our history,
        # we can record it.
        if result_c >= 0 or draw_position not in history:
            self._cached_moves[pos] = (other_c, suit_c, result_c)

        return other, suit, result, draw_position
Exemplo n.º 9
0
 def __init__(self):
     self.cards = Cards()
     self.playerCounter = 0
     self.player = [None, None, None, None]
     self.started = 0
     self.now_player = 0
     self.pass_cnt = 0
     self.pre_cards = []
     self.game_args = [0, 0, 0]
Exemplo n.º 10
0
 def __init__(self, primal=None, kicker=None) -> None:
     self.primal = primal
     self.kicker = kicker
     if primal is None:
         self.primal = Primal()
     if kicker is not None:
         Cards.__init__(self, self.primal.card_num + kicker.card_num, 'num')
     else:
         Cards.__init__(self, self.primal.card_num, 'num')
Exemplo n.º 11
0
class App(object):
    def __init__(self):
        self.name = 'mongoaudit'
        self.version = __version__
        check_version(self.version)
        urwid.set_encoding("UTF-8")
        self.cards = Cards(self)
        self.setup_view()
        self.main()

    def setup_view(self):
        placeholder = urwid.SolidFill()
        self.loop = urwid.MainLoop(placeholder,
                                   PALETTE,
                                   unhandled_input=self.key_handler)
        self.loop.widget = urwid.AttrMap(placeholder, 'bg')
        #self.loop.widget._command_map['tab'] = 'cursor down'
        #self.loop.widget._command_map['shift tab'] = 'cursor up'
        self.loop.screen.set_terminal_properties(colors=256)
        self.cards.welcome()

    def render(self, card):
        div = urwid.Divider()
        rdiv = urwid.AttrMap(div, 'header')
        header = urwid.Filler(urwid.Pile([rdiv, rdiv, rdiv, rdiv, rdiv]),
                              valign='top')
        h1_text = urwid.Text(('h1', self.name))
        h2_text = urwid.Text(('h2', 'v' + self.version), align='right')
        hg_text = urwid.AttrMap(
            urwid.Padding(urwid.Columns([h1_text, h2_text]),
                          left=2,
                          right=2,
                          align='center'), 'header')
        body = urwid.Pile([hg_text, rdiv, card, div])
        widget = urwid.Overlay(body,
                               header,
                               'center',
                               76,
                               'top',
                               'pack',
                               top=1)
        self.loop.widget.original_widget = widget

    @staticmethod
    def key_handler(key):
        if key in ('q', 'Q', 'esc'):
            raise urwid.ExitMainLoop()
        elif key == 'ctrl r':
            python = sys.executable
            os.execl(python, python, *sys.argv)

    def main(self):
        try:
            self.loop.run()
        except KeyboardInterrupt:
            return 0
Exemplo n.º 12
0
    def __init__(self, agents, display, rules):
        self.is_game_over = False
        # This class will maintain all of the cards
        self.cards_handler = Cards()
        self.display = display
        self.rules = rules

        self.game_state = GameState(agents, rules)
        self.game_board = self.game_state.get_game_board()
        self.agents = agents
Exemplo n.º 13
0
    def round_up(self):
        self.first_player = self.player_list[self.round % self.player_count]

        for player in self.player_list:
            Cards.dast_bede(self.round)

        for i in range(self.round):
            self.set_up()

        self.round += 1
Exemplo n.º 14
0
 def next_move(self, this: int, cards: Cards,
               history: Set[int]) -> Tuple[int, int]:
     number_of_players = cards.number_of_players()
     while True:
         other = randrange(number_of_players - 1)
         if other >= this:
             other += 1  # randomly selected other player
         card = randrange(number_of_players)
         if cards.legal(other, card, this, False):
             return other, card
Exemplo n.º 15
0
    def start_game(self):
        playing = True
        button = 0

        while playing:
            Cards.shuffle(self.deck)
            playing = self.play_hand(button)
            print(self.player_to_funds)
            button += 1

        self.print_players()
Exemplo n.º 16
0
def test_deck_setup():
    """
    RED GREEN REFACTOR 
    a (failing) sanity test layout
    """
    deck = Deck()
    assert len(deck) == 52
    assert Cards("A", "s") in deck.cards
    assert Cards("6", "d") in deck.cards
    assert Cards("J", "h") in deck.cards
    assert Cards("T", "c") in deck.cards
Exemplo n.º 17
0
    def find_multiple(cards: Cards, level_to_beat: int, cards_to_find: int):
        """
        :param cards:
        :param level_to_beat:
        :param cards_to_find:
        :rtype: Combination
        """

        if cards_to_find <= 0 or cards_to_find > 4:
            raise ValueError('Illegal combination_type %s' % cards_to_find)

        if cards_to_find == 1:
            for card in (cards - Phoenix()).cards:
                if card.power > level_to_beat:
                    return Combination(cards_list=[card])

            # if no card could have been player, try to take the lead with your Phoenix
            # Phoenix can not be played on a Dragon
            if cards.phoenix_flag and level_to_beat < Dragon().power:
                return Combination(cards_list=[Phoenix()])

        # TODO - TO REFACTOR WITH LOGIC
        if cards_to_find == 2:
            for i in range(len(cards.cards) - 1):
                card = cards.cards[i]
                if card.power > level_to_beat and card.power == cards.cards[
                        i + 1].power:
                    return Cards(cards_list=[card, cards.cards[i + 1]])

        if cards_to_find == 3:
            for i in range(len(cards.cards) - 2):
                card = cards.cards[i]
                if card.power > level_to_beat and card.power == cards.cards[
                        i + 2].power:
                    return Cards(cards_list=[
                        card, cards.cards[i + 1], cards.cards[i + 2]
                    ])

        if cards_to_find == 4:
            for i in range(len(cards.cards) - 3):
                card = cards.cards[i]
                if card.power > level_to_beat and card.power == cards.cards[
                        i + 3].power:
                    return Cards(cards_list=[
                        card, cards.cards[i +
                                          1], cards.cards[i +
                                                          2], cards.cards[i +
                                                                          3]
                    ])

        # If no combination found, try to use Phoenix to play
        if cards.phoenix_flag and 1 <= cards_to_find < 4 and cards.size > 1:
            return Hand.find_multiple(cards - Phoenix(), level_to_beat,
                                      cards_to_find - 1) + Phoenix()
Exemplo n.º 18
0
 def __init__(self):
     """initialize all variables"""
     self.dealer = -1
     self.deck = Cards()
     self.players = []  #this array contains only players, not viewers
     self.n_play = len(self.players)  #number of current players
     self.cur_player = None  #the player on whom the action rests
     self.min_bet = 0  #the current minimum a player must bet
     self.pot = 0  #the current value of the pot
     self.no_raise = 1  #true if the hand has not yet been raised
     self.calls = 0  #number of current calls
Exemplo n.º 19
0
    def find_straight(cards, level_to_beat, length=None, bomb=False):
        """
        1/ Start at level_to_beat - length +2:
        if level_to_beat is 10, length 6, their straight starts at 5, your straight has to start at 6
        2/ see if you can find a straight that beats that
        3/ see if you can find a length-1 straight at level_to_beat -1
        """
        # Get all possible start points for the straight
        if length is None:
            length = 5
        elif length <= 0:
            return None

        start_point = max(1, level_to_beat - length + 2)
        max_strength_power = Dragon().power - 1
        max_start_point = max_strength_power - length + 2
        start_points = range(start_point, max_start_point + 1)

        for card in cards.cards:
            for start in start_points:
                if card.power == start:
                    if length == 1:
                        return Cards(cards_list=[card])
                    else:
                        # TODO - jump in straights
                        # Issue constantly increasing threshold
                        rest = Hand.find_straight(cards - card,
                                                  card.power + length - 2,
                                                  length - 1,
                                                  bomb=bomb)

                        # TODO BOMB
                        if rest:
                            if not rest.phoenix_flag:
                                if min(rest.cards).power == card.power + 1:
                                    return rest + card
                            elif (len(rest.cards) == 1
                                  and Phoenix() in rest.cards) or min(
                                      (rest - Phoenix()
                                       ).cards).power <= card.power + 2:
                                return rest + card

        if cards.phoenix_flag:
            if length == 1:
                return Cards(cards_list=[Phoenix()])

            rest = Hand.find_straight(cards - Phoenix(),
                                      level_to_beat,
                                      length - 1,
                                      bomb=bomb)
            if rest:
                return rest + Phoenix()
Exemplo n.º 20
0
    def calculate_best_choose(self):
        """!@brief Calculation best choose in deck
        """

        self.sortByValue(self.hand_cards)

        resource_hand = [Cards(0, 0) for x in range(0, CONST.get_size_of_hand)]

        for i in range(0, CONST.get_size_of_hand):
            desk_card = Cards(self.desk_cards[i].getCardValue(),
                              self.desk_cards[i].getCardType())
            resource_hand[i] = desk_card
            self.calculateHandValues(resource_hand, i + 1, 0)
Exemplo n.º 21
0
def new_card():
    work = True
    add_card = Cards()
    add_card.create_card()
    while work == True:
        add_another_card = input('Do you want to add another card? y/n ')
        if add_another_card.lower() == 'y':
            new_card()
        elif add_another_card.lower() == 'n':
            print('Done, back to selection list')
            work = False
            game_on()
        else:
            print('Not a valid entry')
Exemplo n.º 22
0
def list_subject():
    list = True
    list_cards = Cards()
    list_cards.display_cards()
    while list == True:
        list_cards_again = input('\nDo you want to list cards again? y/n ')
        if list_cards_again.lower() == 'y':
            list_subject()
        elif list_cards_again.lower() == 'n':
            print('\nDone, back to selection list')
            list = False
            game_on()
        else:
            print('Not a valid entry')
Exemplo n.º 23
0
 def __init__(self,
              arg=None,
              ctype=None,
              chain_len=None,
              num=None,
              kicker_type=None,
              kicker_len=None,
              bomb=False) -> None:
     Cards.__init__(self, arg, ctype)
     self.num = num
     self.chain_len = chain_len
     self.bomb = bomb
     self.kicker_type = kicker_type
     self.kicker_len = kicker_len
Exemplo n.º 24
0
def update_card():
    edit = True
    edit_cards = Cards()
    edit_cards.edit_card()
    while edit == True:
        update_another_card = input('Do you want to edit another card? y/n ')
        if update_another_card.lower() == 'y':
            update_card()
        elif update_another_card.lower() == 'n':
            print('Done, back to selection list')
            edit = False
            game_on()
        else:
            print('Not a valid entry')
Exemplo n.º 25
0
 def __init__(self, gui):
     self.dealer = -1
     self.players = []
     self.gui = gui
     self.deck = Cards()
     self.pot = 0
     self.cur_player = None
     self.min_bet = 0
     self.calls = 0
     self.active_hands = 0
     self.comm_cards = []        #community cards
     self.no_raise = 1           #set to false if somebody has raised the
                                 #big blind
     self.big_blind = 0          #denotes the big blind
     self.hand_over = 0          #true if the hand is over
Exemplo n.º 26
0
def stack_won(game):
    """Have the stack be won by the previous player. Nonmutating.

    Additionally, change the next player to the winning player.
    """
    (player_cards, stack, next_player, winner) = game
    player_cards = player_cards.copy()
    winning_player = dec_player(next_player)
    # NOTE The stack is effectively turned upside down and put underneath
    player_cards[winning_player] = Cards(player_cards[winning_player] + stack)
    stack = Cards()

    next_player = winning_player

    return Game(player_cards, stack, next_player)
Exemplo n.º 27
0
 def reset(self):
     self.partner = None
     self.cards = Cards()
     self.discarded = Cards()
     self.trump = None
     self.is_playing = False
     #We wan't to record what the possible cards are for every player
     self.unknown_cards = [create_deck(), create_deck(), create_deck()]
     #possible_cards[0] is the player next, [1] is our mate, and [2] is the player before us
     index = self.index
     self.unknown_cards[0].owner = (1 + index) % 4
     self.unknown_cards[1].owner = (2 + index) % 4
     self.unknown_cards[2].owner = (3 + index) % 4
     self.mystery_cards = create_deck()
     self.mate_prefered_colors = []
Exemplo n.º 28
0
def setup_table():
    """
    Fixture that sets up a table with a single player.

    """
    r = HouseRules(
        shoe_size=4,
        bet_limits=[10, 500],
        s17=True,
        blackjack_payout=1.5,
        max_hands=4,
        double_down=True,
        split_unlike_tens=True,
        double_after_split=True,
        resplit_aces=False,
        insurance=True,
        late_surrender=True,
        dealer_shows_hole_card=True
    )
    c = Cards(rules=r)
    t = Table()
    p = Player(
        name='Player 1',
        rules=r,
        bankroll=100,
        min_bet=10
    )
    t.add_player(player=p)
    p.set_hand()
    p.stats.create_count_key(count_key=0)
    return c, t, r, p
Exemplo n.º 29
0
    def find_all_straights(cards: Cards):
        #TODO fix levels
        #TODO, put the level in there to differentiate phoenix at start and end
        #TODO Sort the combinations
        # remove Dog and Dragon from any straights
        cards = cards - Dog() - Dragon()

        buckets = Cards.bucketize_hands(cards.cards)
        power_values = buckets.keys()
        possible_straights_power_values = []

        # Get all possible power combinations
        for start in range(Mahjong().power, Dragon().power):

            length = 0
            current_straight_values = []

            for next_value in range(start, Dragon().power):
                found = False
                new_value = None

                if next_value in power_values:
                    found = True
                    new_value = next_value

                elif Phoenix().power in power_values and Phoenix().power not in current_straight_values:
                    if next_value != 1:
                        found = True
                        new_value = Phoenix().power

                if found and new_value not in current_straight_values:
                    current_straight_values.append(new_value)
                    length += 1
                    if length >= 5:
                        possible_straights_power_values.append(current_straight_values.copy())

                elif not found:
                    break

        # Now that we have the powers, we get all possible straights
        straights = []
        for straight in possible_straights_power_values:
            straight_cards = [buckets[power] for power in straight]
            for combinations in itertools.product(*straight_cards):
                # straights.append(Cards(cards_list=list(combinations)))
                straights.append(Combination(cards_list=list(combinations)))

        # We replace the phoenix in all the straights where we can
        new_straights = []
        for straight in straights:
            if Phoenix() not in straight.cards:
                for card in straight.cards:
                    if not card == Mahjong():
                        new_cards = straight-card+Phoenix()
                        new_combo = Combination(cards_list=new_cards.cards)
                        new_straights.append(new_combo)
                        # new_straights.append(straight - card + Phoenix())
        straights.extend(new_straights)
        straights.sort()
        return straights
Exemplo n.º 30
0
 def __str__(self):
   ret = self.typeToString(self.type) + 's ' + Cards.cardToString(self.card)
   if self.target != None:
     ret += ' on team ' + str(self.target)
   if self.coupFourre:
     ret += ' as a coup fourre!'
   return ret
Exemplo n.º 31
0
    def __init__(self):
        """
            INIT
        """
	# pygame - setup 
        pygame.init()
        self.FPS = 30
        self.clock = pygame.time.Clock()
        self.size = (600, 500)
        self.center = (300, 250)
        self.screen = pygame.display.set_mode(self.size)

        self.card_imgs= []
        self.balance = 100
        self.bet_amount = 5
        self.cm = Cards()
        
        self.reset()

        self.key_pressed = "stop"
        self.key_pressed_hold = ""
        self.player_rect_clip = pygame.Rect(0, 0, 75, 100)
        self.stage = 0
        self.step = 0
        self.last_mouse = (0, 0)

        # set up fonts
        self.basicFont = pygame.font.SysFont(None, 48)
        self.subFont = pygame.font.SysFont(None, 24)
        self.subsubFont = pygame.font.SysFont(None, 12)

        self.card_layout_play()
Exemplo n.º 32
0
    def has_card(self, this: int, other: int, suit: int, cards: Cards,
                 history: Set[int]) -> bool:
        forced, has = cards.has_card(suit, this, other)
        if forced:
            return has

        return randrange(2) == 1
Exemplo n.º 33
0
def test_dealer_plays_hand(s17, dealer_hand, expected):
    """
    Tests the dealer_plays_hand function when a dealer hits or stands
    on soft 17.

    """
    r = HouseRules(
        shoe_size=4,
        bet_limits=[10, 500],
        s17=s17
    )
    c = Cards(rules=r)
    t = Table()
    p = Player(
        name='Player 1',
        rules=r,
        bankroll=100,
        min_bet=10
    )
    t.add_player(player=p)
    p.stats.create_count_key(count_key=0)

    dealer_hand = dealer_plays_hand(
        rules=r,
        cards=c,
        dealer_hole_card=dealer_hand[1],
        dealer_hand=dealer_hand
    )

    assert dealer_hand == expected
Exemplo n.º 34
0
 def __init__(self):
     """initialize all variables"""
     self.dealer = -1
     self.deck = Cards()
     self.players = []       #this array contains only players, not viewers
     self.n_play = len(self.players)  #number of current players
     self.cur_player = None  #the player on whom the action rests
     self.min_bet = 0        #the current minimum a player must bet
     self.pot = 0            #the current value of the pot
     self.no_raise = 1       #true if the hand has not yet been raised
     self.calls = 0          #number of current calls
Exemplo n.º 35
0
    def find_all_multiples(cards: Cards, multiple: int):
        cards = cards - Dog() - Dragon()
        buckets = Cards.bucketize_hands(cards.cards)
        multiples = []
        for level in range(Mahjong().power+1, Dragon().power):
            cards_this_level = buckets[level]
            if (Phoenix().power in buckets.keys()) and (multiple != 4):
                cards_this_level.append(Phoenix())
            if len(cards_this_level) > 1:
                for pair in itertools.combinations(cards_this_level, multiple):
                    multiples.append(Combination(cards_list=list(pair)))

        return multiples
Exemplo n.º 36
0
    def __init__(self):
        """
            INIT
        """     
        self.bet_amount = 5 # default bet is 5
        
        self.stage = "title"  # play, title, help
        
        self.title_b = self.make_button(self.goto_play_screen, "cards/play.png")
        self.help_b = self.make_button(self.goto_play_screen, "cards/play.png")
        self.play_b = self.make_button(self.goto_help_screen, "cards/help.png")
        self.play_coin = self.make_button(self.set_bet_10, "cards/5coin.png")
        

        self.message = "Click deal."
        self.balance = 100
        self.cm = Cards()
        self.content_mode=ui.CONTENT_SCALE_ASPECT_FIT
        self.card_imgs=[]
        self.buttons=[]
        self.step = 0
        self.card_button = [self.card1_button, self.card2_button, self.card3_button, self.card4_button, self.card5_button,]
        self.reset()
    
        self.buttons.append(self.make_button(self.button_tapped, "cards/deal.png"))     
        
        self.score_label  = ui.Label()
        self.score_label.x = 150
        self.score_label.y = 450
        self.score_label.height = 30
        self.score_label.width = 100
        self.score_label.text = "Balance: "

        self.score_value_label  = ui.Label()
        self.score_value_label.x = 250 
        self.score_value_label.y = 450
        self.score_value_label.height = 30
        self.score_value_label.width =75
        self.score_value_label.text = "$" + str(self.balance)
        self.score_value_label.background_color = (55,55,55)

        self.winning_label  = ui.Label()
        self.winning_label.x = 250 
        self.winning_label.y = 350
        self.winning_label.height = 30
        self.winning_label.width =175
        self.winning_label.text = self.message
Exemplo n.º 37
0
class Game():
    """
        GAME - class
        class implements UI for videopoker in pygame.
    """
    def __init__(self):
        """
            INIT
        """
	# pygame - setup 
        pygame.init()
        self.FPS = 30
        self.clock = pygame.time.Clock()
        self.size = (600, 500)
        self.center = (300, 250)
        self.screen = pygame.display.set_mode(self.size)

        self.card_imgs= []
        self.balance = 100
        self.bet_amount = 5
        self.cm = Cards()
        
        self.reset()

        self.key_pressed = "stop"
        self.key_pressed_hold = ""
        self.player_rect_clip = pygame.Rect(0, 0, 75, 100)
        self.stage = 0
        self.step = 0
        self.last_mouse = (0, 0)

        # set up fonts
        self.basicFont = pygame.font.SysFont(None, 48)
        self.subFont = pygame.font.SysFont(None, 24)
        self.subsubFont = pygame.font.SysFont(None, 12)

        self.card_layout_play()


    def card_layout_play(self):
        self.card_rects = []
        self.card_rects.append(pygame.Rect(20, 10, 75, 100))
        self.card_rects.append(pygame.Rect(20, 105, 75, 100))
        self.card_rects.append(pygame.Rect(20, 200, 75, 100))
        self.card_rects.append(pygame.Rect(20, 295, 75, 100))
        self.card_rects.append(pygame.Rect(20, 390, 75, 100))

        self.deal_rect = pygame.Rect(200, 200, 75, 100)
        self.deal_card = pygame.transform.scale(pygame.image.load("cards/deal.png"),(72, 90))

        self.bet_rect = pygame.Rect(200, 105, 75, 100)
        self.bet_card = pygame.transform.scale(pygame.image.load("cards/5coin.png"),(72, 90))

        self.help_rect = pygame.Rect(200, 10, 75, 100)
        self.help_card = pygame.transform.scale(pygame.image.load("cards/help.png"),(72, 90))


    def reset(self):
        """
           RESET 
        """
        self.deck = self.cm.shuffledeck(self.cm.opendeck())

        # for testing, call for particular hands:
        # self.deck = self.cm.test_hand("four of a kind")

        self.card_imgs=[]
        for i in range (0,5):
            self.card_imgs.append(pygame.transform.scale(pygame.image.load("cards/back.png"),(72, 90)))


        self.hand =[None,None,None,None,None,]
        self.card_locks = [False, False, False, False, False]
        self.message = 'Set bet and click deal.'


    def handle_events(self):
        """
            HANDLE EVENTS - keys and mouse clicks
        """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYUP:
                        if event.key == pygame.K_ESCAPE:
                            self.key_pressed = "esc"
                        elif event.key == pygame.K_F1:
                            self.key_pressed = "help"
                        elif event.key == pygame.K_SPACE:
                            self.key_pressed = "space"
                        else:
                            pass
            if event.type == pygame.MOUSEBUTTONUP:
                self.last_mouse = event.pos 
                self.key_pressed_hold = self.key_pressed
                self.key_pressed = "mouse"

    def cardN_button(self,n):
        """
            CARD pressed - flip card 
        """
        if self.step == 2 or self.step == 0:
           pass
        else:
           if self.hand[n].is_dealt:
                self.card_imgs[n] = pygame.transform.scale(pygame.image.load("cards/"+self.hand[n].display+".png"),(72, 90))
                self.card_locks[n] = True
                self.hand[n].is_dealt = False
           else:
                self.card_imgs[n] = pygame.transform.scale(pygame.image.load("cards/back.png"),(72, 90))
                self.card_locks[n] = False
                self.hand[n].is_dealt = True

    def score_hand(self):
        """
         SCORE HAND
        """
        vodds = vp_odds()
        x,s = vodds.calculate_payout(self.hand, self.bet_amount)
        self.message = s + ' pays: $'+ str(x)
        return x


    def deal_tapped(self):
        """
            DEAL button tapped.
        """
        if self.step == 2:
            self.reset()
            self.step = 0
            self.message = 'Set bet, press deal.'
        else:
            self.step += 1
            self.message = 'Pick, and deal.'
            hand = self.cm.deal(5,self.deck)
            for i in range(0,5):
                if not self.card_locks[i]:
                    self.hand[i] = hand[i]
                    self.card_imgs[i] = pygame.transform.scale(pygame.image.load("cards/"+hand[i].display+".png"),(72, 90))

            self.card_locks = [True, True, True, True, True]
            if self.step == 2:
                self.balance += self.score_hand()
            if self.balance <= 0:
                self.stage = 3 

    def bet_next(self):
        """
            BET changed
        """
        if self.step !=0:
            return

        if self.bet_amount == 5 :
            self.bet_amount = 10
            self.bet_card = pygame.transform.scale(pygame.image.load("cards/10coin.png"),(72, 90))
        elif self.bet_amount == 10:
            self.bet_amount = 20
            self.bet_card = pygame.transform.scale(pygame.image.load("cards/20coin.png"),(72, 90))
        elif self.bet_amount == 20:
            self.bet_amount = 5
            self.bet_card = pygame.transform.scale(pygame.image.load("cards/5coin.png"),(72, 90))
        else:
            pass


    def draw_stage1(self):
        """
            DRAW STAGE 1 - Play Screen
        """
        self.screen.fill(BLUE)
        
        for i in range(0, len(self.card_imgs)):
            self.screen.blit(self.card_imgs[i], self.card_rects[i], self.player_rect_clip)

        self.screen.blit(self.deal_card, self.deal_rect, self.player_rect_clip)
        self.screen.blit(self.bet_card, self.bet_rect, self.player_rect_clip)
        self.screen.blit(self.help_card, self.help_rect, self.player_rect_clip)
    
        for i in range(0, len(self.card_imgs)):
            if self.card_rects[i].collidepoint(self.last_mouse):
                self.cardN_button(i)
                self.last_mouse = (-1, -1)
                break

        if self.deal_rect.collidepoint(self.last_mouse):
            self.last_mouse = (-1, -1)
            self.deal_tapped()

        if self.bet_rect.collidepoint(self.last_mouse):
            self.last_mouse = (-1, -1)
            self.bet_next()

        if self.help_rect.collidepoint(self.last_mouse):
            self.last_mouse = (-1, -1)
            self.key_pressed ="help"

        self.stage1_text = self.basicFont.render(self.message, True, WHITE, BLUE)
        textRect = self.stage1_text.get_rect()
        textRect.x = 220
        textRect.y = 320
        self.screen.blit(self.stage1_text, textRect)
        
        balance = "Current balance is: " + str(self.balance)
        balance_text = self.subFont.render(balance, True, WHITE, BLUE)
        textRect = self.stage1_text.get_rect()
        textRect.x = 220
        textRect.y = 400
        self.screen.blit(balance_text, textRect)


    def draw_stage0(self):
        """
            DRAW STAGE 0 - Title/Splash 
        """
        # set up the text
        self.stage0_text = self.basicFont.render('Welcome to Video Poker', True, WHITE, BLACK)
        self.stage0_subtext1 = self.subFont.render('Press SPACE to Continue', True, WHITE, BLACK)
        self.stage0_subtext2 = self.subFont.render('F1 for help Or ESC to exit', True, WHITE, BLACK)

        self.screen.fill(BLACK)
        if self.key_pressed == "space":
            self.stage = 1

        textRect = self.stage0_text.get_rect()
        textRect.center = self.center
    
        textRect.centery -= 150
        self.screen.blit(self.stage0_text, textRect)        

        textRect.centery += 50
        self.screen.blit(self.stage0_subtext1, textRect)

        textRect.centery += 20
        self.screen.blit(self.stage0_subtext2, textRect)

    def draw_stage2(self):
        """
            DRAW STAGE 2 - Help
        """
        # set up the text
        self.stage2_text = self.basicFont.render('Video Poker - Help', True, WHITE, GREEN)
        self.stage2_subtext1 = self.subFont.render('Press SPACE to Continue', True, WHITE, BLACK)

        self.screen.fill(GREEN)

        if self.key_pressed == "space":
            self.stage = 1

        textRect = self.stage2_text.get_rect()
        textRect.center = self.center

        textRect.centery -= 200
        self.screen.blit(self.stage2_text, textRect)

        sub_text = "Press SPACE to Play"
        xtext_rect = self.subFont.render(sub_text, True, WHITE, GREEN)
        sub_text_rect = xtext_rect.get_rect()
        sub_text_rect.center = self.center
        sub_text_rect.centery -= 175
        self.screen.blit(xtext_rect, sub_text_rect)

        # get the list of odds from the odds machine
        v = vp_odds()
        odds = v.list_odds()
        for i in range(0, len(odds)):
            text  = odds[i]
            xtext = self.subFont.render(text, True, WHITE, GREEN)
            textRect = xtext.get_rect()
            textRect.x = 120
            textRect.y = 120 + i*30
            self.screen.blit(xtext, textRect)


    def draw_stage3(self):
        """
            DRAW STAGE 3 - Broke
        """
        self.screen.fill(BLUE)
        if self.key_pressed == "space":
            self.stage = 1
        notes = []
        notes.append("You have run out of money!")
        notes.append("I will credit you 100 dollars.")
        notes.append("Press space to continue")
        notes.append("or ESC to return to the title screen")
        for i in range(0, len(notes)):
            text  = notes[i]
            xtext = self.subFont.render(text, True, WHITE, BLUE)
            textRect = xtext.get_rect()
            textRect.x = 120
            textRect.y = 120 + i*30
            self.screen.blit(xtext, textRect)
        self.balance = 100


    @staticmethod
    def main():
        x = Game()
        x.run()

    def run(self):
        """
            RUN - main loop.
        """
        while True:
            self.handle_events()
            if self.key_pressed == "esc" and self.stage == 0:
                pygame.quit()
                sys.exit()
            if self.key_pressed == "esc" and self.stage != 0:
                self.key_pressed = "none"
                self.stage = 0
            if self.key_pressed == "help" and self.stage !=2:
                self.direcion = "none"
                self.stage = 2
            if self.stage == 0:
                self.draw_stage0()
            elif self.stage == 1:
                self.draw_stage1()
            elif self.stage == 2:
                self.draw_stage2()  
            elif self.stage == 3:
                self.draw_stage3()  
            else:
                pass

            self.clock.tick(self.FPS)
            pygame.display.update()
Exemplo n.º 38
0
from cards import Cards

c = Cards()

c.game()

Exemplo n.º 39
0
class MyView(ui.View):

    def cardN_button(self,n):
        if self.step == 2 or self.step == 0:
            pass
        else:
            if self.hand[n].is_dealt:
                self.card_imgs[n] = self.make_button(self.card_button[n], 'cards/'+self.hand[n].display+'.png') 
                self.card_locks[n] = True
                self.hand[n].is_dealt = False
            else:
                self.card_imgs[n] = self.make_button(self.card_button[n], 'cards/back.png')
                self.card_locks[n] = False
                self.hand[n].is_dealt = True
        self.set_needs_display()
    
    def card1_button(self, sender):
        self.cardN_button(0)

    def card2_button(self, sender):
        self.cardN_button(1)

    def card3_button(self, sender):
        self.cardN_button(2)

    def card4_button(self, sender):
        self.cardN_button(3)

    def card5_button(self, sender):
        self.cardN_button(4)

    def set_bet_5(self, sender):
        if self.step ==0:
            self.bet_amount = 5
            self.play_coin = self.make_button(self.set_bet_10, "cards/5coin.png")
            self.set_needs_display()

    def set_bet_10(self, sender):
        if self.step ==0:
            self.bet_amount = 10
            self.play_coin = self.make_button(self.set_bet_20, "cards/10coin.png")
            self.set_needs_display()

    def set_bet_20(self, sender):
        if self.step ==0:
            self.bet_amount = 20
            self.play_coin = self.make_button(self.set_bet_5, "cards/20coin.png")
            self.set_needs_display()

        
    def __init__(self):
        """
            INIT
        """     
        self.bet_amount = 5 # default bet is 5
        
        self.stage = "title"  # play, title, help
        
        self.title_b = self.make_button(self.goto_play_screen, "cards/play.png")
        self.help_b = self.make_button(self.goto_play_screen, "cards/play.png")
        self.play_b = self.make_button(self.goto_help_screen, "cards/help.png")
        self.play_coin = self.make_button(self.set_bet_10, "cards/5coin.png")
        

        self.message = "Click deal."
        self.balance = 100
        self.cm = Cards()
        self.content_mode=ui.CONTENT_SCALE_ASPECT_FIT
        self.card_imgs=[]
        self.buttons=[]
        self.step = 0
        self.card_button = [self.card1_button, self.card2_button, self.card3_button, self.card4_button, self.card5_button,]
        self.reset()
    
        self.buttons.append(self.make_button(self.button_tapped, "cards/deal.png"))     
        
        self.score_label  = ui.Label()
        self.score_label.x = 150
        self.score_label.y = 450
        self.score_label.height = 30
        self.score_label.width = 100
        self.score_label.text = "Balance: "

        self.score_value_label  = ui.Label()
        self.score_value_label.x = 250 
        self.score_value_label.y = 450
        self.score_value_label.height = 30
        self.score_value_label.width =75
        self.score_value_label.text = "$" + str(self.balance)
        self.score_value_label.background_color = (55,55,55)

        self.winning_label  = ui.Label()
        self.winning_label.x = 250 
        self.winning_label.y = 350
        self.winning_label.height = 30
        self.winning_label.width =175
        self.winning_label.text = self.message
        #self.winning_label.background_color = (55,55,55)
        
    def score_hand(self):
        """
            SCORE HAND
        """
        vodds = vp_odds()
        x,s = vodds.calculate_payout(self.hand, self.bet_amount)
        self.message = s + ' pays: $'+ str(x)
        return x
        
        
    def button_tapped(self, sender):        
        if self.step == 2:
            self.reset()
            self.step = 0
            self.message = 'Deal for next hand.'
        else:
            self.step += 1
            self.message = 'Pick, and deal.'
            hand = self.cm.deal(5,self.deck)
            
            for i in range(0,5):        
                if not self.card_locks[i]:
                    self.hand[i] = hand[i]
                    self.remove_subview(self.card_imgs[i])
                    self.card_imgs[i] = self.make_button(self.card_button[i], 'cards/'+hand[i].display+'.png')

            self.card_locks = [True, True, True, True, True]
            if self.step == 2:
                self.balance += self.score_hand()
                if self.balance <= 0:
                    self.stage = 'broke'
                self.score_value_label.text = "$" + str(self.balance)

        self.set_needs_display()
        
    def make_button(self, callback, image):
        button = ui.Button()     
        button.width = 72
        button.height = 90
        button.background_image = ui.Image.named(image)
        button.flex = 'LRTB'                                  
        button.action = callback
        return button                      

    def reset(self):
        """
            RESET 
        """
        self.deck = self.cm.shuffledeck(self.cm.opendeck())
        
        # for testing, call for particular hands:
        # self.deck = self.cm.test_hand("four of a kind")
        
        self.card_imgs=[]
        for i in range (0,5):
            self.card_imgs.append(self.make_button(self.card_button[i], "cards/back.png"))

        self.hand =[None,None,None,None,None,]
        self.card_locks = [False, False, False, False, False]
        self.message = 'Click deal.'
        

    def did_load(self):
        pass
    
    def will_close(self):
        pass
        
    def goto_play_screen(self, sender):
        self.stage = "play"
        self.set_needs_display()

    def goto_help_screen(self, sender):
        self.stage = "help"
        self.set_needs_display()
        
    def draw(self):
        """
            DRAW
        """
        # self.bounds =(0,0,320,504)
        # print self.width,',',self.height
        path = ui.Path.rect(0,0,self.width, self.height)
        ui.set_color('brown')
        path.fill()
        # ui.set_color('green')
        # path.line_width=30
        # path.stroke()
        
        # Remove all the current sub views.
        for i in self.subviews:
            self.remove_subview(i)
            
        if self.stage == "play":
            
            
            for i in range(0,len(self.card_imgs)):
                self.card_imgs[i].center = (82, 50+100*i)
                self.add_subview(self.card_imgs[i])
            x = self.width * 0.5 + 100
            y = self.height * 0.5 
            for i in range(0,len(self.buttons)):
                self.buttons[i].center = (x, y + 100*i) 
                self.add_subview(self.buttons[i])

            self.add_subview(self.score_label)
            self.score_value_label.x = 225
            self.add_subview(self.score_value_label)
            self.winning_label.x = 150
            self.winning_label.text = self.message
            
            self.add_subview(self.winning_label)
            
            self.play_coin.center = (x,y-100)
            self.add_subview(self.play_coin)
            
            self.play_b.center = (x,y-200)
            self.add_subview(self.play_b)
            
        if self.stage == "help":
            # add in our views
            self.add_subview(self.help_b)
            tit = ui.Label()
            tit.x = 100
            tit.y = 0
            tit.height = 60
            tit.width = 500
            tit.text = "Video Poker - Help"
            self.add_subview(tit)
            
            v = vp_odds()
            list_odds = v.list_odds()
            for i in range(0, len(list_odds)):
                x = ui.Label()
                x.x = 10
                x.y = 100 + i*30
                x.height = 30
                x.width = 350
                x.text = list_odds[i]
                self.add_subview(x)
                
        
        if self.stage == "title":
            tit = ui.Label()
            tit.x = 100
            tit.y = 0
            tit.height = 60
            tit.width = 500
            tit.text = "- Video Poker - "
            self.add_subview(tit)

            self.add_subview(self.title_b)
        
        if self.stage == 'broke':
            tit = ui.Label()
            tit.x = 100
            tit.y = 0
            tit.height = 60
            tit.width = 500
            tit.text = "- Video Poker - "
            self.add_subview(tit)

            self.add_subview(self.title_b)
            self.balance = 100
            self.score_value_label.text = "$" + str(self.balance)
            list_text = ['You are broke!','I will credit you 100 dollars,','Press play to continue.']
            for i in range(0, len(list_text)):
                x = ui.Label()
                x.x = 10
                x.y = 100 + i*30
                x.height = 30
                x.width = 350
                x.text = list_text[i]
                self.add_subview(x)
            
            
    def layout(self):
        pass
    
    def touch_began(self, touch):
        pass
    
    def touch_moved(self, touch):
        pass
    
    def touch_ended(self, touch):
        pass
        
    def keyboard_frame_will_change(self,frame):
        pass
    
    def keyboard_frame_did_change(self, frame):
        pass
Exemplo n.º 40
0
class HoldEmRef:
    """the successor to the PokerRef class."""
    def __init__(self):
        """initialize all variables"""
        self.dealer = -1
        self.deck = Cards()
        self.players = []       #this array contains only players, not viewers
        self.n_play = len(self.players)  #number of current players
        self.cur_player = None  #the player on whom the action rests
        self.min_bet = 0        #the current minimum a player must bet
        self.pot = 0            #the current value of the pot
        self.no_raise = 1       #true if the hand has not yet been raised
        self.calls = 0          #number of current calls


    ###
    #public functions
    ###

    def set_players(self, players):
        """players should be an array of types derived from PokerPlayer

        These should be people sitting at the table, not viewers of the game"""
        self.players = players
        self.n_play = len(self.players)

    def rem_player(self, p):
        """remove a player from the game"""

    def get_blinds(self, ante, blind):
        """get the blinds and ante from the players"""
        self._init_hand()
        if ante:
            for p in self.players:
                p.payAnte(ante)
                self.transmit_bet(p, ante)
        sb = int(round(blind/2.0))
        small = self.next_active(self.dealer)
        self.big_blind = self.next_active(small)
        if not small.payBlind(sb): raise "blind error"
        if not self.big_blind.payBlind(blind): raise "blind error"
        self.transmit_bet(small, sb)
        self.transmit_bet(self.big_blind, blind)
        self.min_bet = blind
        self.cur_player = self.next_active(self.big_blind)

    def get_next_bet(self):
        """get the next player's bet"""
        self.cur_player.transmitBet(self.min_bet - self.cur_player.active_bet)

    def deal(self):
        """deal the cards to the players"""
        for p in self.players: p.re_init()
        cards = self.deck.deal(self.n_play*2)
        if self.dealer == -1:
            #pick a random player
            self.dealer = self.players[self.deck.randint(0, self.n_play-1)]
        else: self.dealer = self.next_active(self.dealer)
        cur_player = self.next_active(self.dealer)
        for card in cards:
            cur_player.addCard(card)
            cur_player = self.next_active(cur_player)

    ###
    #private functions
    ###

    def _init_hand(self):
        """reinitialize the values needed for the hand"""
        self.n_play = len(self.players)
        self.cur_player = None
        self.min_bet = 0
        self.pot = 0
        self.no_raise = 1
        self.calls = 0
        for p in self.players: p.active = 1
        self.active_players = self.n_play

    def count_active(self):
        count = 0
        for p in self.players:
            if p.active: count += 1
        return count

    def next_active(self, p):
        """return the next to play after p"""
        if not type(3) == type(p): p = p.position
        p = self.players[(p+1) % self.n_play]
        while not p.active: p = self.players[(p+1) % self.n_play]
        return p

    def transmit_bet(self, player, bet):
        for p in self.players:
            p.receiveBet(bet, p.position)

    def receive_bet(self, bet, player):
        p = self.players[player]
        p.active_bet += bet
        if p.active_bet < self.min_bet and bet != -1:
            p.active_bet -= bet
            raise BetTooSmallError
        if p.active_bet > p.money:
            p.active_bet -= bet
            raise BetTooBigError
        if bet == -1: self._fold(p)
        elif p.active_bet == self.min_bet: self._call(p, bet)
        else: self._raise(p, bet)
        self.transmit_bet(p, bet)
        self.cur_player = self.next_active(self.cur_player)

    def _fold(self, player):
        player.active_bet = 0
        player.active = 0
        self.active_players -= 1
        if not self.active_players: self.endHand()

    def _call(self, player, bet):
        """handle a player's call"""
        self.pot += player.active_bet
        player.money -= bet
        self.calls += 1
        if self.calls >= self.active_players and not self._big_blind_exempt():
            if len(self.comm_cards) == 0: self.deal_comm_cards(3)
            elif len(self.comm_cards) == 3: self.deal_comm_cards(1)
            elif len(self.comm_cards) == 4: self.deal_comm_cards(1)
            else: self.endHand()
        else: self.get_next_bet()

    def deal_comm_cards(self, n): pass
    
    def _big_blind_exempt(self):
        """return true if this is the special case where the big blind gets to
        raise his bet. We already know calls > active_players"""
        if len(self.comm_cards) == 0\
            and self.cur_player.position == self.big_blind.position\
            and self.no_raise:
            return 1
        return 0
            
    def _raise(self, player, bet):
        """handle a player's raise"""
        self.min_bet = player.active_bet
        self.pot += bet
        player.money -= bet
        self.calls = 0
        self.no_raise = 0
Exemplo n.º 41
0
class TestCards(unittest.TestCase):



    def setUp(self):
        self.cards = Cards()
        self.cards.open(':memory:')

    def tearDown(self):
        self.cards.close()

    def test_getCard(self):
        card1 = Card(1, 'question', 'answer', 'qhint', 'ahint', 13)
        card2 = Card(2, 'frage', 'antwort', 'qhint', 'ahint2', 20)
        id1 = self.cards.addCard(card1)
        id2 = self.cards.addCard(card2)
        card1a = self.cards.getCard(id1)
        card2a = self.cards.getCard(id2)
        self.assertEqual(card1, card1a)
        self.assertEqual(card2, card2a)


    def test_getCardCount(self):
        self.cards.addCard(Card(None, 'co', 'tutaj'))
        self.cards.addCard(Card(None, 'ale', 'fajnie'))
        self.assertEqual(self.cards.getCardsCount(), 2)


    def test_deleteCard(self):
        id1 = self.cards.addCard(Card(None, 'one', 'eins'))
        id2 = self.cards.addCard(Card(None, 'two', 'zwei'))
        id3 = self.cards.addCard(Card(None, 'three', 'drei'))
        # delete card 1, check if other exist
        self.cards.deleteCard(id1)
        self.assertFalse(self.cards.existsCard(id1))
        self.assertTrue(self.cards.existsCard(id2))
        self.assertTrue(self.cards.existsCard(id3))
        # add and delete next card
        id4 = self.cards.addCard(Card(4, 'four', 'vier'))
        self.cards.deleteCard(id4)
        self.assertFalse(self.cards.existsCard(id4))
        self.assertTrue(self.cards.existsCard(id2))
        self.assertTrue(self.cards.existsCard(id3))


    def test_updateCard(self):
        id1 = self.cards.addCard(Card(None, 'one', 'eins'))
        id2 = self.cards.addCard(Card(None, 'two', 'zwei'))
        id3 = self.cards.addCard(Card(None, 'three', 'drei'))
        # update second card and check if update is successful
        # and the other cards are intact
        self.cards.updateCard(Card(id2, 'two!', 'zwei!'))
        self.assertEqual(self.cards.getCard(id2), Card(id2, 'two!', 'zwei!'))
        self.assertEqual(self.cards.getCard(id1), Card(id1, 'one', 'eins'))
        self.assertEqual(self.cards.getCard(id3), Card(id3, 'three', 'drei'))


    def test_getCardHeaders(self):
        id1 = self.cards.addCard(Card(None, 'one', 'eins'))
        id2 = self.cards.addCard(Card(None, 'two', 'zwei'))
        id3 = self.cards.addCard(Card(None, 'three', 'drei'))
        id4 = self.cards.addCard(Card(None, 'four', 'vier'))
        id5 = self.cards.addCard(Card(None, 'five', 'fuenf'))
        id6 = self.cards.addCard(Card(None, 'six', 'sechs'))
        id7 = self.cards.addCard(Card(None, 'seven', 'sieben'))
        id8 = self.cards.addCard(Card(None, 'eight', 'acht'))
        id9 = self.cards.addCard(Card(None, 'nine', 'neun'))
        # retrieve card from rownum 0 to 0
        cards = self.cards.getCardHeaders('', 0, 1)
        self.assertEqual(len(cards), 1)
        self.assertEqual(cards[0], (1, 'one'))
        # retrieve cards from rownum 1 to 1
        cards = self.cards.getCardHeaders('', 1, 2)
        self.assertEqual(len(cards), 1)
        self.assertEqual(cards[0], (2, 'two'))
        # retrieve cards from rownum 2 to 4
        cards = self.cards.getCardHeaders('', 2, 6)
        self.assertEqual(len(cards), 4)
        self.assertEqual(cards[0], (3, 'three'))
        self.assertEqual(cards[1], (4, 'four'))
        self.assertEqual(cards[2], (5, 'five'))
        self.assertEqual(cards[3], (6, 'six'))

        # delete some and check retrieve again
        # retrieve cards < 7
        self.cards.deleteCard(id3)
        self.cards.deleteCard(id4)
        cards = self.cards.getCardHeaders('ID < 7', 2, 4)
        self.assertEqual(len(cards), 2)
        self.assertEqual(cards[0], (5, 'five'))
        self.assertEqual(cards[1], (6, 'six'))

        # add some cards and check retrieve again
        # retrieve last 3 cards
        id10 = self.cards.addCard(Card(None, 'ten', 'zehn'))
        id11 = self.cards.addCard(Card(None, 'eleven', 'einzehn'))
        id12 = self.cards.addCard(Card(None, 'twelve', 'zwoelf'))
        cards = self.cards.getCardHeaders('', 7, 13)
        self.assertEqual(len(cards), 3)
        self.assertEqual(cards[0], (id10, 'ten'))
        self.assertEqual(cards[1], (id11, 'eleven'))
        self.assertEqual(cards[2], (id12, 'twelve'))

        # check for query when no range is added
        cards = self.cards.getCardHeaders()
        self.assertEqual(len(cards), 10)

        # check for assertion error when invalid minrow, maxrow
        self.assertRaises(AssertionError, self.cards.getCardHeaders, '', 4, 1)
Exemplo n.º 42
0
 def setUp(self):
     self.cards = Cards()
     self.cards.open(':memory:')
Exemplo n.º 43
0
class PokerRef:
    def __init__(self, gui):
        self.dealer = -1
        self.players = []
        self.gui = gui
        self.deck = Cards()
        self.pot = 0
        self.cur_player = None
        self.min_bet = 0
        self.calls = 0
        self.active_hands = 0
        self.comm_cards = []        #community cards
        self.no_raise = 1           #set to false if somebody has raised the
                                    #big blind
        self.big_blind = 0          #denotes the big blind
        self.hand_over = 0          #true if the hand is over

    def mainLoop(self):
        while 1:
            self.deal()
            self.cur_player = (self.dealer + 1) % len(self.players)
            while not self.hand_over:
                self.getNextBet(self.nextActive(self.cur_player))
                self.gui.Update()
                #assure that the bet has been received before proceeding
            self.hand_over = 0

    def nextActive(self, cur):
        cur = (cur + 1) % len(self.players)
        while self.players[cur].active == 0:
            cur = (cur + 1) % len(self.players)
        return cur

    def countActive(self):
        count = 0
        for p in self.players:
            if p.active: count += 1
        return count

    def newGame(self, players, blind, ante):
        """start a new game

        players is an array with a string. 'h' means human player, for now.
        blind is the size of the small blind. The big will be assumed to be
            twice that.
        ante is the size of the ante.
        """
        self.players = players
        self.blind = blind
        self.ante = ante
        for i in range(len(players)):
            if players[i] == 'h': 
                players[i] = PokerHuman(10000, "player%s" % i, i)
            elif players[i] == 'b': 
                players[i] = PokerBot(10000, "player%s" % i, i, self)
            elif players[i] == None: pass
            else: raise "illegal player"
        self.gui.setUpPlayers(players)
        self.dealer = -1
        self.deal()

    def cardsToCmpName(self, cards):
        outCards = []
        for card in cards:
            b = int(card[:-1]) + 2
            if b > 9:
                if b == 10:
                    b = 't'
                elif b == 11:
                    b = 'j'
                elif b == 12:
                    b = 'q'
                elif b == 13:
                    b = 'k'
                elif b == 14:
                    b = 'a'
            outCards.append(str(b) + card[-1:])
        return outCards

    def getWinner(self):
        self.winner = []
        cmd = './mycmpn '
        self.eval_hands = []
        positions = []
        for p in self.players:
            if p.active:
                positions.append(p.position)
                for card in self.cardsToCmpName(p.getHand()):
                    cmd += '%s ' % card
        cmd += '-- '
        for card in self.cardsToCmpName(self.comm_cards):
            cmd += '%s ' % card
        output = commands.getoutput(cmd).split()
        print cmd, "\n", output
        if len(output) == 1:
            win_pos = positions[int(output[0])]
            self.players[win_pos].money += self.pot
            self.winner.append(win_pos)
        else:
            split = int(self.pot) / len(output)
            for i in output:
                win_pos = positions[int(i)]
                self.players[win_pos].money += split
                self.winner.append(win_pos)
        return self.winner
 
    def endHand(self):
        """code to run at the end of a hand"""
        print "ending hand"
        self.winner = []
        if self.active_hands == 1:
            self.players[self.nextActive(0)].money += self.pot
            self.winner.append(self.nextActive(0))
        else: self.winner = self.getWinner()
        self.gui.clearTable(self.winner, self.pot, self.players)
        self.deck.reset()
        for p in self.players: p.endHand(self.winner)
        self.pot = 0
        self.cur_player = self.dealer
        self.min_bet = 0
        self.calls = 0
        self.active_hands = 0
        self.no_raise = 1
        self.comm_cards = []
        self.gui.refreshMoney(self.players)
        self.hand_over = 0
        self.deal()

    def deal(self):
        """deal 2 cards to each player"""
        cards = self.deck.deal(len(self.players)*2)
        if self.dealer == -1:
            self.dealer = 8
            #self.dealer = self.deck.randint(0, len(self.players)-1)
        else: self.dealer = (self.dealer + 1) % len(self.players)
        count = 1
        for card in cards:
            cur_player = (self.dealer + count) % len(self.players)
            self.players[cur_player].addCard(card)
            count += 1
        self.getBlinds()
        self.gui.deal(self.players, self.dealer)
        self.active_hands = self.countActive()
        self.gui.refreshPot(self.pot)
        self.cur_player = (self.dealer + 2) % len(self.players)
        self.gui.fireBetEvent()

    def getBlinds(self):
        small_blind = (self.dealer + 1) % len(self.players)
        self.big_blind = (small_blind + 1) % len(self.players)
        for p in self.players:
            if p.position == small_blind:
                if p.payBlind(self.blind): 
                    p.receiveBet(self.big_blind, self.blind * 2)
                else: raise "what to do if they don't accept the blind?"
            elif p.position == self.big_blind:
                if p.payBlind(self.blind * 2): 
                    p.receiveBet(small_blind, self.blind)
                else: raise "what to do if they don't accept the blind?"
            else:
                p.receiveBet(small_blind, self.blind)
                p.receiveBet(self.big_blind, self.blind * 2)
        self.gui.refreshMoney(self.players)
        self.pot += self.blind * 3
        self.min_bet = self.blind * 2

    def dealCommCards(self, num):
        """Deal num community cards"""
        print "dealing %d community cards" % num
        self.min_bet = 0
        self.calls = 0
        cards = self.deck.deal(num)
        for card in cards: self.comm_cards.append(card)
        self.gui.dealCommCards(cards)
        for p in self.players:
            p.receiveCommCards(cards)
            p.active_bet = 0

    def fold(self, p):
        """folds a hand.
        
        p should be an actual reference to the player"""
        print "player %d folds" % p.position
        p.active = 0
        self.gui.clearHand(p.position)
        self.active_hands -= 1
        self.transmitBet(-1, p.position)
        self.gui.refreshMoney(self.players)
        self.gui.refreshPot(self.pot)
        if self.active_hands == 0 or self.active_hands - 1 == self.calls:
            self.hand_over = 1
            self.endHand()
        else: self.gui.fireBetEvent()

    def raiseBet(self, bet, p):
        """performs a raise.
        
        bet should be a bet amount
        p should be a reference to a player"""
        print "player %d raises to $%d" % (p.position, bet)
        self.pot += bet
        p.money -= bet
        self.calls = 0
        self.no_raise = 0
        self.min_bet = p.active_bet
        self.transmitBet(bet, p.position)
        self.gui.refreshMoney(self.players)
        self.gui.refreshPot(self.pot)
        self.gui.fireBetEvent()

    def callBet(self, bet, p):
        """performs a call.

        bet should be a bet amount
        p should be a reference to a player"""
        print "player %d calls for $%d. Active: %d. no_raise: %d" % \
            (p.position, bet, p.active_bet, self.no_raise)
        self.pot += bet
        p.money -= bet
        self.calls += 1
        self.transmitBet(bet, p.position)
        self.gui.refreshMoney(self.players)
        self.gui.refreshPot(self.pot)
        #the second condition allows the big blind to bet on the first round
        #if nobody raises to him
        print self.calls, self.active_hands, self.hand_over
        if self.calls >= self.active_hands and not\
            self.isBigBlindBet(self.nextActive(self.cur_player)):
            self.cur_player = self.nextActive(self.dealer)
            if len(self.comm_cards) == 0: 
                self.no_raise = 0           #big blind can only raise 1st round
                self.dealCommCards(3)
            elif len(self.comm_cards) == 3: self.dealCommCards(1)
            elif len(self.comm_cards) == 4: self.dealCommCards(1)
            elif len(self.comm_cards) == 5: 
                self.hand_over = 1
                self.endHand()
        if not self.hand_over: self.gui.fireBetEvent()

    def isBigBlindBet(self, p):
        """returns true if it's big blind's chance to bet on the first round
        
        p is the number of the next player"""
        if p == self.big_blind and self.no_raise and len(self.comm_cards) == 0:
            return 1
        return 0

    def getNextBet(self):
        player = self.nextActive(self.cur_player)
        print "getNextBet from %d" % player
        if self.players[player].type == "HUMAN":
            self.gui.getBet(player, self.min_bet - \
                self.players[player].active_bet)
        else:
            self.players[player].transmitBet(self.min_bet - \
                self.players[player].active_bet)

    def receiveBet(self, bet, player):
        self.cur_player = player
        p = self.players[player]
        if bet > 0: p.active_bet += bet
        if bet < 0: self.fold(p)                #this call has side effects!
        elif p.active_bet < self.min_bet:
            p.active_bet -= bet
            raise BetTooSmallError
        elif p.active_bet > p.money:
            p.active_bet -= bet
            raise BetTooBigError
        elif p.active_bet == self.min_bet: self.callBet(bet, p)
        elif p.active and p.active_bet > self.min_bet:
            self.raiseBet(bet, p)
        else: raise "Something is fscked up!!1!"

    def transmitBet(self, bet, player):
        """transmits a bet to all current players

        bet should be the dollar amount of the bet (<0 for folds)
        player should be the player's position on the table"""
        for p in self.players:
            p.receiveBet(bet, player)
Exemplo n.º 44
0
class CardModel(QAbstractItemModel):
    """Model to be used for list and tree view."""

    class InvalidIndexError(Exception): pass
    class ModelNotActiveError(Exception): pass

    def __init__(self, parent=None):
        QAbstractListModel.__init__(self, parent)
        self.cards = Cards()


    def _checkIndex(self, index):
        if index is None or not index.isValid() or index == QModelIndex():
            raise CardModel.InvalidIndexError, "Invalid index given"

    def _checkActive(self):
        if not self.isActive():
            raise CardModel.ModelNotActiveError, "Model is not active. Use open first."


    def open(self, dbpath):
        self.cards.open(str(dbpath))
        # FIXME why these do not work??
        self.reset()
        # ^ self.emit(SIGNAL('modelReset()'))

    def close(self):
        self.emit(SIGNAL('modelAboutToBeReset()'))
        self.cards.close()
        self.reset()


    def filepath(self):
        """Returns path to currently open database"""
        if self.cards.isOpen():
            return self.cards.db_path
        else:
            return None

    def isActive(self):
        return self.cards.isOpen()


    def parent(self, index):
        return QModelIndex()


    def rowCount(self, parent=QModelIndex()):
        if parent.isValid():
            return 0
        else:
            if self.cards.isOpen():
                return self.cards.getCardsCount()
            else:
                return 0


    def columnCount(self, parent=QModelIndex()):
        if parent.isValid():
            return 0
        else:
            if self.cards.isOpen():
                return 5
            else:
                return 0


    def index(self, row, column, parent=QModelIndex()):
        if row < 0 or column < 0 or not self.cards.isOpen():
            return QModelIndex()
        else:
            #  returns index with given card id
            header = self.cards.getCardHeaders('', row, row + 1)
            if len(header) == 1:
                return self.createIndex(row, column, int(header[0][0]))
            else:
                return QModelIndex()

    # for display role only id+question in following columns will be
    # for specific data , in the following columns

    def data(self, index, role=Qt.DisplayRole):
        self._checkIndex(index)
        if role not in (Qt.DisplayRole, Qt.UserRole):
            return QVariant()

        card = self.cards.getCard(index.internalId())
        if role == Qt.UserRole:
            return card
        else:
            if index.column() == 0:
                return QVariant('#%d %s' % (card.id, str(card.question).strip()))
            elif index.column() == 1:
                return QVariant('%s' % str(card.answer).strip())
            elif index.column() == 2:
                return QVariant('%s' % str(card.question_hint).strip())
            elif index.column() == 3:
                return QVariant('%s' % str(card.answer_hint).strip())
            elif index.column() == 4:
                return QVariant('%s' % str(card.score))
            else:
                return QVariant()


    def flags(self, index):
        return QAbstractListModel.flags(self, index) | Qt.ItemIsEnabled | Qt.ItemIsSelectable


    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                if section == 0:
                    return QVariant("Question")
                elif section == 1:
                    return QVariant("Answer")
                elif section == 2:
                    return QVariant(tr("Question hint"))
                elif section == 3:
                    return QVariant(tr("Answer hint"))
                elif section == 4:
                    return QVariant(tr("Score"))
                else:
                    return QVariant()
            else:
                return QVariant(str(section))
        return QVariant()



    def getPreviousIndex(self, index):
        """Returns previous index before given or given if it's first."""
        self._checkIndex(index)
        if index.row() == 0:
            return index
        else:
            return self.index(index.row() - 1, 0)
        # pointer , get row before


    def getNextIndex(self, index):
        """Returns next index after given or given if it's last."""
        self._checkIndex(index)
        if index.row() == self.rowCount() - 1:
            return index
        else:
            return self.index(index.row() + 1, 0)
        # get row after ?

    # TODO
    # what about inserting rows
    # and moving rows up and down ??
    # must have parameter position or display position ??

    # TODO
    # add special handlers like rowsAboutToBeInserted etc .
    # right now only model to be reset


    def addNewCard(self):
        """Adds a new empty card."""
        self.emit(SIGNAL('modelAboutToBeReset()'))

        rowid = self.cards.addCard(Card())
        # TODO is it ok to return it here?
        result = self.createIndex(self.cards.getCardsCount(), 0, rowid)

        # cards.addCard(Card())
        # TODO
        # why these do not work ?
        self.reset()
        # self.emit(SIGNAL('modelReset()'))
        #
        return result


    def deleteCard(self, index):
        self._checkIndex(index)
        self.emit(SIGNAL('modelAboutToBeReset()'))

        self.cards.deleteCard(index.internalId())

        # why these do not work??
        self.reset()
        # self.emit(SIGNAL('modelReset()'))
        # cards - deleteCard  card_id

    # TODO question
    # how to update card if peg is somewhere else ?
    # maybe keep blob as well ?
    # the items are then splitted
    def updateCard(self, index, question, answer):
        self._checkIndex(index)

        card = Card(index.internalId(), question, answer)
        self.cards.updateCard(card)

        # update data in the model
        self.emit(SIGNAL('dataChanged(QModelIndex)'), index)



    # TODO model should not have any algorithms - it should be just as a proxy
    # between database and any more advanced algorithm
    # e.g. database importer
    # btw. they should use the same classes with the probe program
    # TODO progress bar for importing and possibility to cancel if is a long
    # operatoin
    def importQAFile(self, file, clean=True):
        """Import cards from given question&answer file.
        @param file can be file name or file like object
        """
        self.emit(SIGNAL('modelAboutToBeReset()'))
        self._checkActive()
        if isstring(file):
            file = open(file, 'rt')
        if clean:
            self.cards.deleteAllCards()
        prefix = ''
        last_prefix = ''
        card = Card()
        for line in file.readlines():
            if line.upper().startswith('Q:') or line.upper().startswith('A:'):
                last_prefix = prefix
                prefix = line[:2].upper()
                line = line[3:]
                # if new card then recreate
                if prefix == 'Q:' and prefix != last_prefix:
                    if not card.isEmpty():
                        self.cards.addCard(card, False)
                    card = Card()
                if line.strip() != '':
                    if prefix == 'Q:':
                        card.question += line
                    else: # prefix == a
                        card.answer += line
        # add last card
        if not card.isEmpty():
            self.cards.addCard(card)

        # TODO do it in a real transaction way
        # in case of error do a rollback
        self.cards.commit()
        self.reset()
Exemplo n.º 45
0
 def __init__(self, parent=None):
     QAbstractListModel.__init__(self, parent)
     self.cards = Cards()
Exemplo n.º 46
0
	_print('Warning: Sounds disabled.', 'red')

pygame.init()
screen = pygame.display.set_mode((700, 500))
pygame.display.set_caption('Blackjack')
pygame.mouse.set_visible(0)

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0,153,0,0))

screen.blit(background, (0,0))
pygame.display.flip()

clock = pygame.time.Clock()
c = Cards()
c.shuffle()
print(c.draw())
card1 = Card(c.display(), 315, 10)
print(c.getValue())
v = c.draw()
v = c.display()
card2 = Card('bc.png', 225, 10)
print(c.getValue())
print(c.draw())
card3 = Card(c.display(), 225, 350)
print(c.getValue())
print(c.draw())
card4 = Card(c.display(), 315, 350)
print(c.getValue())