コード例 #1
0
ファイル: test_Deck.py プロジェクト: denversc/cards
 def test_deck_full(self):
     x = Deck()
     x.reset()
     expected_state_after = x[:-1]
     expected_card = x[-1]
     actual_card = x.draw()
     self.assertEqual(actual_card, expected_card)
     self.assertListEqual(x, expected_state_after)
コード例 #2
0
ファイル: test_Deck.py プロジェクト: denversc/cards
 def test_full(self):
     x = Deck()
     x.reset()
     before = list(x)
     x.shuffle()
     after = list(x)
     self.assertTrue(before != after)
     self.assertSetEqual(set(x), set(before))
コード例 #3
0
ファイル: main2.py プロジェクト: orenco9/A1o2F3
def main():
    d = Deck()
    print 'hands:'
    c1 = raw_input('card1?')
    c2 = raw_input('card2?')
    c3 = raw_input('card3?')
    c4 = raw_input('card4?')
    card1 = Card(c1[0], c1[1])
    card2 = Card(c2[0], c2[1])
    card3 = Card(c3[0], c3[1])
    card4 = Card(c4[0], c4[1])
    ps = list()
    ps.append(Hand(card1, card2))
    ps.append(Hand(card3, card4))
    # ps = d.deal_players(N_PLAYERS)
    ps_str = ''
    for p in ps:
        ps_str += str(p) + ', '
    print ps_str

    wins = [0] * N_PLAYERS
    for loop in range(0, N_LOOP):
        d.reset()
        for p in ps:
            d.draw_card(p.card1)
            d.draw_card(p.card2)

        # print "community:"
        com = d.deal_community()
        com_str = ''
        for c in com:
            com_str += str(c) + ', '
        # print com_str

        ss = []
        for i in range(0, N_PLAYERS):
            ss.append(Holdem.showdown_hand_score(ps[i], com))
            # print ps[i], ss[i]
            # # if ss[i][0] == '9':
            # #     exit()
        # print 'best:'
        max_index, max_value = max(enumerate(ss), key=operator.itemgetter(1))
        # print max_index, max_value
        if ss[0] == ss[1]:
            wins[0] += 0.5
            wins[1] += 0.5
        else:
            wins[max_index] += 1  # OCOC what about ties?

    for i_wins in wins:
        print round(float(i_wins) / N_LOOP * 1000) / 10.0
コード例 #4
0
ファイル: CAHGame.py プロジェクト: johnmiked15/scrappy
class CAHGame(object):
    def __init__(self, server, channel):
        self.status = "Waiting for players to join"

        # Keep track of the current channel/server
        self.channel = channel
        self.server = server

        #flag to keep track of whether or not game is running
        self.running = True

        #list of active players in a game
        self.players = []

        #dummy with a small deck for testing.
        #replace with actual card loading from DB later
        self.deck = Deck()

        # Who is the current czar in self.players?
        # Starting at -1 so the first iteration has the czar be the first person to join
        self.current_czar = -1

        # What is the current black card?
        self.current_card = None

        # Cards submitted
        self.submissions = {}

    #add a new player to the game
    def add_player(self, name):
        #check to see if player already in game
        if name in [p.name for p in self.players]:
            return False
        else:
            player = Player(name)
            self.players.append(player)
            self.deal(player)
            return player

    def get_player(self, name):
        players = [p for p in self.players if p.name == name]
        if len(players) == 1:
            return players[0]
        else:
            return None

    #start the game
    def start(self):
        # Reset back to the start
        self.status = "Waiting for player selection"

        # Remove previous submissions from players' hands
        for player, submissions in self.submissions.iteritems():
            for card in submissions:
                if card in player.hand: player.hand.remove(card)

        self.submissions = {}

        # Refresh player hands
        for player in self.players:
            self.deal(player)

        # Deal the new black card
        new_card = self.deal_black()
        if new_card is None:
            self.message("Out of black cards! You played a long game!")
            self.end() # TODO: make this end the game when out of black cards
            return

        czar = self.choose_czar()
        self.message("The new czar is %s" % czar.name)
        self.message("%s has drawn: %s" % (czar.name, self.current_card.body))

        # Show players their current hand
        for player in [player for player in self.players if player.name != czar.name]:
            self.message("You will need to choose \x02%d\x0F cards with the 'select X' command, where X is the card's position in your hand." % self.cards_needed, player)
            if self.cards_needed > 1:
                self.message("NOTE: To submit multiple cards, use the cah command 'select X Y ...', where the card numbers are separated by a space.", player)
            # Display hand
            self.message("Ok, here's your hand:", player)
            for num, card in enumerate(player.hand):
                self.message("%d. %s" % (num+1, card.body), player)

    def end(self):
        #check if game is already running
        if self.running:
            self.message("The game has ended.")
            for place, player in enumerate(sorted(self.players, key=lambda x: x.score, reverse=True)):
                self.message("%d. %s with %d points" % (place+1, player.name, player.score))
            self.running = False
            self.deck.reset()
        else:
            self.message("There's no game running!  Use '@cah new' to start a new game.")

    # Choose cards to play
    def select(self, player, cards):
        # Fail if the player is the Czar OR it's not time for players to select cards
        if self.status != "Waiting for player selection" or self.players[self.current_czar].name == player.name:
            self.message("This isn't your turn!", player)
            return

        # Fail if player didn't select the right amount of cards
        if len(cards) != self.cards_needed:
            self.message("You need to play %d cards _only_" % self.cards_needed, player)
            return

        # Fail if cards are invalid (they should have been sanitized to ints in cah.py)
        for card in cards:
            if card > len(player.hand) or card <= 0:
                self.message("You don't have a card %d in your hand!" % card, player)
                return

        # Insert cards into the submissions dictionary
        self.submissions[player] = [player.hand[card-1] for card in cards]

        # Continue on in the game loop if all but the czar have voted
        if len(self.submissions) == len(self.players)-1:
            self.display_selections()
            self.status = "Waiting for Czar vote"

    # Present the funnies
    def display_selections(self):
        self.message("Results are in!")
        # Question cards are only displayed once, then the replies are presented as choices
        if "_" not in self.current_card.body:
            self.message(self.current_card.body)
            for num, submission in enumerate(self.submissions.values()):
                self.message("%d. %s" % (num+1, ', '.join([x.body for x in submission])))
        # Other cards have the white card answeres filled in the blanks (with bold and underline)
        else:
            for num, submission in enumerate(self.submissions.values()):
                replacements = []
                filled_in = self.current_card.body.replace("%","%%").replace("_", "%s")
                for i in range(self.cards_needed):
                    replacements.append("\x02\x1F%s\x0F" % submission[i].body)
                filled_in = filled_in % tuple(replacements)
                self.message("%d. %s" % (num+1, filled_in))

        # Prompt the czar to not be lazy...
        self.message("Now for %s to vote..." % self.players[self.current_czar].name)

    # Czar vote
    def vote(self, player, vote):
        # Fail if the player isn't the current Czar
        if player.name != self.players[self.current_czar].name:
            self.message("You are not the Czar!", player)
            return

        # Fail if it's not time for the Czar to vote
        if self.status != "Waiting for Czar vote":
            self.message("We're not ready for you to vote.", player)
            return

        # Fail if the czar vote for a choice that isn't present
        if vote <= 0 or vote > len(self.players)-1:
            self.message("%d isn't a valid vote selection." % vote, player)
            return

        # Display and increase score for the Czar's choice
        winning_player = self.submissions.keys()[vote-1]
        self.message("%s won this round! The winning combination was..." % winning_player.name)

        winning_player.score += 1

        # TODO: refactor this and the bit in display_selections
        # see display_selections, this is the same, except it only displays a single submission
        if "_" not in self.current_card.body:
            self.message(self.current_card.body)
            self.message(', '.join([x.body for x in self.submissions.values()[vote-1]]))
        else:
            replacements = []
            filled_in = self.current_card.body.replace("%","%%").replace("_", "%s")
            for i in range(self.cards_needed):
                replacements.append("\x02\x1F%s\x0F" % self.submissions.values()[vote-1][i].body)
            filled_in = filled_in % tuple(replacements)
            self.message(filled_in)

        # And start the game loop over
        self.start()

    #deal cards to player until hand size is 10
    def deal(self, player):
        handSize = len(player.hand)

        while handSize < 10:
            player.hand.append(self.deck.draw("white"))
            handSize += 1

        return player.hand

    def choose_czar(self):
        self.current_czar = (self.current_czar + 1) % len(self.players)
        return self.players[self.current_czar]

    def deal_black(self):
        try:
            self.current_card = self.deck.draw("black")
            return self.current_card
        except NoMoreCards:
            return None

    def message(self, body, player=None):
        if player is not None:
            self.server.notice(player.name, body)
        else:
            self.server.privmsg(self.channel, body)

    @property
    def cards_needed(self):
        return self.current_card.num_answers
コード例 #5
0
ファイル: proj10.py プロジェクト: Tempade/python-projects
def main(): #Function that brings all other functions together in one place
    '''main function'''
    RULES = '''
    Basra Card Game:
        This game belongs to a category of card games called “fishing cards games”. 
        Each player in turn matches a card from their hand with one (or more) of those 
        lying face-up on the table and then takes them. 
        If the card which the player played out does not match one of the existing cards, 
        it stays on the table.
    To win, you have to collect more points.'''
    
    print(RULES) 
    D = Deck()
    p1_cards = [] # card in hands player1
    p2_cards = [] #card in hands player2
    t_cards = []   # card on the floor
    p1_pile = [] # for player1
    p2_pile = [] # for player2
    basra_1 = []
    basra_2 = []
    p1_turn = (0,2,4,6)
    p2_turn = (1,3,5,7)
    game = True
    game_quit = False
    
    answer = input("Would you like to play? y/Y or n/N?")
    while answer!='n':
        print(" ---------Start The game--------")
        D.shuffle()
        while game == True: #replace by the correct condition
            for rounds in range(6):
                if rounds == 0:
                    distribute_cards(D,p1_cards,p2_cards,t_cards,True)
                    print('Dealing the cards, 4 cards for each player, 4 cards on the table')
                    print('Cards left:  {}'.format(D.__len__()))
                    display_table(t_cards,p1_cards,p2_cards)
                else:
                    distribute_cards(D,p1_cards,p2_cards,t_cards,False)
                    print('')
                    print('------Start new round-----')
                    print('Dealing the cards, 4 cards for each player')
                    print('Cards left:  {}'.format(D.__len__()))
                    display_table(t_cards,p1_cards,p2_cards)
                for turn in range(8):
                    while turn in p1_turn:
                        card_index = input("Player {:d} turn: -> ".format(1))
                        if card_index == 'q':
                            game = False
                            game_quit = True
                            break
                        try:
                            play(p1_cards[int(card_index)],p1_cards,p1_pile,basra_1,t_cards)
                        except:
                            print('Please enter a valid card index, 0 <= index <= {:d}'.format(len(p1_cards)-1))
                        else:
                            display_table(t_cards,p1_cards,p2_cards)
                            break
                    if game_quit == True:
                        break
                    while turn in p2_turn:
                        card_index = input("Player {:d} turn: -> ".format(2))
                        if card_index == 'q':
                            game = False
                            game_quit = True
                            break
                        try:
                            play(p2_cards[int(card_index)],p2_cards,p2_pile,basra_2,t_cards)
                        except:
                            print('Please enter a valid card index, 0 <= index <= {:d}'.format(len(p2_cards)-1))
                        else:
                            display_table(t_cards,p1_cards,p2_cards)
                            break
                    if game_quit == True:
                        break
                turn = 0
                if t_cards != []:
                    if game == True:
                        if turn in p1_turn:
                            p1_pile.append(t_cards)
                        else:
                            p2_pile.append(t_cards)
                        t_cards = []
                        display_table(t_cards,p1_cards,p2_cards)
                if game == False:
                    break
            if D.is_empty() == True:
                display_table(t_cards,p1_cards,p2_cards)
                score = compute_score(p1_pile,p2_pile,basra_1,basra_2)
                print('player 1:  {}'.format(score[0]))
                print('player 2:  {}'.format(score[1]))
                print('')
                if score[0] > score[1]:
                    print('Player 1 is the winner')
                    game = False
                else:
                    print('Player 2 is the winner')
                    game = False
                    
# useful strings to match tests (put them in a loop to reprompt on bad input)
# print('Please enter a valid card index, 0 <= index <= {:d}'.format(len(p1_cards)-1))
# card_index = input("Player {:d} turn: -> ".format(turn))

# remember to clear the data structures before the next game
# deck.reset()
# p1_cards.clear() # card in hands player1
# p2_cards.clear() #card in hands player2
# t_cards.clear()   # card on the floor
# p1_pile.clear() # pile for player1
# p2_pile.clear() # pile for player2
# basra_1.clear() # basra for player1
# basra_2.clear() #basra for player2
        if game_quit == True:
            break
        answer = input("Would you like to play? y/Y or n/N? ")
        if answer.lower() == 'y':
            D.reset()
            p1_cards.clear() # card in hands player1
            p2_cards.clear() #card in hands player2
            t_cards.clear()   # card on the floor
            p1_pile.clear() # pile for player1
            p2_pile.clear() # pile for player2
            basra_1.clear() # basra for player1
            basra_2.clear() #basra for player2
    print('Thanks for playing. See you again soon.')
コード例 #6
0
class Session:
    def __init__(self, n_bbs, bb_size, rake_size, strategies):
        self.n_bbs = n_bbs
        self.bb_size = bb_size
        self.rake_size = rake_size

        self.n_spots = 0
        self.rake_accum = 0

        self.players = []
        for strategy in strategies:
            self.players.append(
                Player(
                    len(self.players) + 1, strategy, START_BALANCE,
                    n_bbs * bb_size))
        self.n_players = len(self.players)
        self.dealer_idx = self.n_players - 1  # Start with the first player as SB
        self.deck = Deck()

    def run(self, n_spots):
        self.report()
        for i in range(n_spots):
            self.handle_spot()
            self.dealer_idx = (self.dealer_idx + 1) % self.n_players
            self.report()
        self.report()

    def handle_spot(self):
        self.n_spots += 1
        self.deck.reset()
        hands = self.deck.deal_players(self.n_players)

        for h in hands:
            print h

        balances = [0] * self.n_players
        for i_player in range(self.n_players):
            player_idx = (self.dealer_idx + POS_UTG_VS_DEALER +
                          i_player) % self.n_players
            balances[i_player] = self.players[player_idx].table_balance

        bet_sizes = [0] * self.n_players
        pot_size = 0
        player_sb_idx = (self.dealer_idx + POS_SB_VS_DEALER) % self.n_players
        bet_sizes[player_sb_idx] = self.players[player_sb_idx].bet(
            self.bb_size / 2)  # SB
        pot_size += bet_sizes[player_sb_idx]
        player_bb_idx = (self.dealer_idx + POS_BB_VS_DEALER) % self.n_players
        bet_sizes[player_bb_idx] = self.players[player_bb_idx].bet(
            self.bb_size)  # BB
        pot_size += bet_sizes[player_bb_idx]

        allin_participants = []
        for i_player in range(self.n_players):
            if i_player == self.n_players - 1 and len(allin_participants) == 0:
                break  # When no one bet and last player to act

            player_idx = (self.dealer_idx + POS_UTG_VS_DEALER +
                          i_player) % self.n_players
            is_allin = self.players[player_idx].act(hands[player_idx],
                                                    balances,
                                                    POSITIONS_LIST[i_player],
                                                    None)
            if is_allin:
                bet_sizes[player_idx] += self.players[player_idx].go_allin()
                pot_size += bet_sizes[player_idx]
                allin_participants.append({
                    'player_idx': player_idx,
                    'hand': hands[player_idx],
                    'bet': bet_sizes[player_idx]
                })
            else:
                balances[i_player] = 0

        if len(allin_participants) == 0:
            player_idx = (self.dealer_idx + POS_BB_VS_DEALER) % self.n_players
            self.players[player_idx].eval_walk(pot_size)
        elif len(allin_participants) == 1:
            player_idx = allin_participants[0]['player_idx']
            self.players[player_idx].eval_spot_result(
                allin_participants[0]['bet'], pot_size)
        else:
            com = self.deck.deal_community()
            for c in com:
                print c
            hand_ranks = []
            for i in range(0, len(allin_participants)):
                hand_ranks.append(
                    Holdem.showdown_hand_score(allin_participants[i]['hand'],
                                               com))

            # OCOC evaluate hand ranks and side pots...
            participant_bets = [item['bet'] for item in allin_participants]
            participant_wins = Holdem.distribute_pot(hand_ranks,
                                                     participant_bets)
            for i in range(0, len(allin_participants)):
                player_idx = allin_participants[i]['player_idx']
                self.players[player_idx].eval_spot_result(
                    allin_participants[i]['bet'], participant_wins[i])

    def report(self):
        for pl in self.players:
            print pl
        print sum([p.wallet_balance + p.table_balance for p in self.players])
コード例 #7
0
ファイル: CAHGame.py プロジェクト: jdrouhard/scrappy
class CAHGame(object):
    def __init__(self, server, channel):
        self.status = "Waiting for players to join"

        # Keep track of the current channel/server
        self.channel = channel
        self.server = server

        #flag to keep track of whether or not game is running
        self.running = True

        #list of active players in a game
        self.players = []

        #dummy with a small deck for testing.
        #replace with actual card loading from DB later
        self.deck = Deck()

        # Who is the current czar in self.players?
        # Starting at -1 so the first iteration has the czar be the first person to join
        self.current_czar = -1

        # What is the current black card?
        self.current_card = None

        # Cards submitted
        self.submissions = {}

    #add a new player to the game
    def add_player(self, name):
        #check to see if player already in game
        if name in [p.name for p in self.players]:
            return False
        else:
            player = Player(name)
            self.players.append(player)
            self.deal(player)
            return player

    def get_player(self, name):
        players = [p for p in self.players if p.name == name]
        if len(players) == 1:
            return players[0]
        else:
            return None

    #start the game
    def start(self):
        # Reset back to the start
        self.status = "Waiting for player selection"

        # Remove previous submissions from players' hands
        for player, submissions in self.submissions.iteritems():
            for card in submissions:
                if card in player.hand: player.hand.remove(card)

        self.submissions = {}

        # Refresh player hands
        for player in self.players:
            self.deal(player)

        # Deal the new black card
        new_card = self.deal_black()
        if new_card is None:
            self.message("Out of black cards! You played a long game!")
            self.end()  # TODO: make this end the game when out of black cards
            return

        czar = self.choose_czar()
        self.message("The new czar is %s" % czar.name)
        self.message("%s has drawn: %s" % (czar.name, self.current_card.body))

        # Show players their current hand
        for player in [
                player for player in self.players if player.name != czar.name
        ]:
            self.message(
                "You will need to choose \x02%d\x0F cards with the 'select X' command, where X is the card's position in your hand."
                % self.cards_needed, player)
            if self.cards_needed > 1:
                self.message(
                    "NOTE: To submit multiple cards, use the cah command 'select X Y ...', where the card numbers are separated by a space.",
                    player)
            # Display hand
            self.message("Ok, here's your hand:", player)
            for num, card in enumerate(player.hand):
                self.message("%d. %s" % (num + 1, card.body), player)

    def end(self):
        #check if game is already running
        if self.running:
            self.message("The game has ended.")
            for place, player in enumerate(
                    sorted(self.players, key=lambda x: x.score, reverse=True)):
                self.message("%d. %s with %d points" %
                             (place + 1, player.name, player.score))
            self.running = False
            self.deck.reset()
        else:
            self.message(
                "There's no game running!  Use '@cah new' to start a new game."
            )

    # Choose cards to play
    def select(self, player, cards):
        # Fail if the player is the Czar OR it's not time for players to select cards
        if self.status != "Waiting for player selection" or self.players[
                self.current_czar].name == player.name:
            self.message("This isn't your turn!", player)
            return

        # Fail if player didn't select the right amount of cards
        if len(cards) != self.cards_needed:
            self.message(
                "You need to play %d cards _only_" % self.cards_needed, player)
            return

        # Fail if cards are invalid (they should have been sanitized to ints in cah.py)
        for card in cards:
            if card > len(player.hand) or card <= 0:
                self.message("You don't have a card %d in your hand!" % card,
                             player)
                return

        # Insert cards into the submissions dictionary
        self.submissions[player] = [player.hand[card - 1] for card in cards]

        # Continue on in the game loop if all but the czar have voted
        if len(self.submissions) == len(self.players) - 1:
            self.display_selections()
            self.status = "Waiting for Czar vote"

    # Present the funnies
    def display_selections(self):
        self.message("Results are in!")
        # Question cards are only displayed once, then the replies are presented as choices
        if "_" not in self.current_card.body:
            self.message(self.current_card.body)
            for num, submission in enumerate(self.submissions.values()):
                self.message("%d. %s" %
                             (num + 1, ', '.join([x.body
                                                  for x in submission])))
        # Other cards have the white card answeres filled in the blanks (with bold and underline)
        else:
            for num, submission in enumerate(self.submissions.values()):
                replacements = []
                filled_in = self.current_card.body.replace("%", "%%").replace(
                    "_", "%s")
                for i in range(self.cards_needed):
                    replacements.append("\x02\x1F%s\x0F" % submission[i].body)
                filled_in = filled_in % tuple(replacements)
                self.message("%d. %s" % (num + 1, filled_in))

        # Prompt the czar to not be lazy...
        self.message("Now for %s to vote..." %
                     self.players[self.current_czar].name)

    # Czar vote
    def vote(self, player, vote):
        # Fail if the player isn't the current Czar
        if player.name != self.players[self.current_czar].name:
            self.message("You are not the Czar!", player)
            return

        # Fail if it's not time for the Czar to vote
        if self.status != "Waiting for Czar vote":
            self.message("We're not ready for you to vote.", player)
            return

        # Fail if the czar vote for a choice that isn't present
        if vote <= 0 or vote > len(self.players) - 1:
            self.message("%d isn't a valid vote selection." % vote, player)
            return

        # Display and increase score for the Czar's choice
        winning_player = self.submissions.keys()[vote - 1]
        self.message("%s won this round! The winning combination was..." %
                     winning_player.name)

        winning_player.score += 1

        # TODO: refactor this and the bit in display_selections
        # see display_selections, this is the same, except it only displays a single submission
        if "_" not in self.current_card.body:
            self.message(self.current_card.body)
            self.message(', '.join(
                [x.body for x in self.submissions.values()[vote - 1]]))
        else:
            replacements = []
            filled_in = self.current_card.body.replace("%", "%%").replace(
                "_", "%s")
            for i in range(self.cards_needed):
                replacements.append(
                    "\x02\x1F%s\x0F" %
                    self.submissions.values()[vote - 1][i].body)
            filled_in = filled_in % tuple(replacements)
            self.message(filled_in)

        # And start the game loop over
        self.start()

    #deal cards to player until hand size is 10
    def deal(self, player):
        handSize = len(player.hand)

        while handSize < 10:
            player.hand.append(self.deck.draw("white"))
            handSize += 1

        return player.hand

    def choose_czar(self):
        self.current_czar = (self.current_czar + 1) % len(self.players)
        return self.players[self.current_czar]

    def deal_black(self):
        try:
            self.current_card = self.deck.draw("black")
            return self.current_card
        except NoMoreCards:
            return None

    def message(self, body, player=None):
        if player is not None:
            self.server.notice(player.name, body)
        else:
            self.server.privmsg(self.channel, body)

    @property
    def cards_needed(self):
        return self.current_card.num_answers