コード例 #1
0
class CardMatch:
    def __init__(self, card_players):
        self.card_players = card_players
        self.deck = Deck()
        self.deck.shuffle()
        for pl in card_players:
            pl.stats.card_games += 1

    def get_winner(self):
        rank_players = sorted(self.card_players,
                              key=lambda x: x.stats.aces,
                              reverse=True)
        if len(rank_players) > 1:
            if rank_players[0].stats.aces == rank_players[1].stats.aces:
                return None
        return rank_players[0] if rank_players else None

    def playing(self, player: CardPlayer):
        if self.deck.has_cards():
            card_picked = self.deck.take_card()
            player.stats.cards.append(card_picked)
            if card_picked.rank == Ranks.ACE:
                player.stats.aces += 1
            return True
        else:
            return False
コード例 #2
0
    def card_game(self, card_match):
        """Card Game"""
        self.render_background()
        deck = Deck()
        deck.shuffle()

        if not card_match.card_players:
            self.render_text("There are no Card Players... Restart the game",
                             (620, 300))
        else:
            while card_match.deck.has_cards():
                for p in card_match.card_players:
                    width_c = 500
                    if card_match.playing(p):
                        self.render_background()
                        self.show_player_scores(card_match.card_players)
                        self.render_image(self.player_pic, (450, 350))
                        self.render_text(p.first_name, (450, 320))
                        pos = 1
                        for card in p.stats.cards:
                            self.render_image(self.card_images[str(card)],
                                              (width_c + 70 * pos, 350))
                            pos += 1

                        pygame.display.flip()
                        time.sleep(0.1)
                    else:
                        return
コード例 #3
0
 def test_deck_shuffle(self):
     deck = Deck()
     random.seed(2020)
     before = deck.cards.copy()
     deck.shuffle()
     after = deck.cards.copy()
     self.assertCountEqual(before, after)
     self.assertNotEqual(before, after)
コード例 #4
0
class DeckTestCase(TestCase):
    def setUp(self):
        self.deck = Deck()
        self.test_cards = [
            Card('London', 'Blue'),
            Card('Washington', 'Yellow'),
            Card('Bejing', 'Red'),
            Card('Moscow', 'Black'),
            Card('New York', 'Yellow'),
        ]
        self.deck.cards = self.test_cards.copy()

    def test_prepare(self):
        self.deck.prepare('fake settings')
        self.assertEqual([], self.deck.cards)
        self.assertEqual([], self.deck.discard)

    def test_take_top_card(self):
        card = self.deck.take_top_card()
        self.assertEqual('London', card.name)

        next_card = self.deck.take_top_card()
        self.assertEqual('Yellow', next_card.colour)

    def test_take_bottom_card(self):
        card = self.deck.take_bottom_card()
        self.assertEqual('Yellow', card.colour)

        next_card = self.deck.take_bottom_card()
        self.assertEqual('Moscow', next_card.name)

    def test_add_card(self):
        new_card = Card('Cherepovets', 'Black')
        self.deck.add_card(new_card)

        self.assertEqual('Cherepovets', self.deck.cards[-1].name)

    def test_add_discard(self):
        discarded_card = Card('Cherepovets', 'Black')
        self.deck.add_discard(discarded_card)

        self.assertEqual('Cherepovets', self.deck.discard[-1].name)

    def test_shuffle(self):
        random.seed(42)
        random.shuffle(self.test_cards)

        random.seed(42)
        self.deck.shuffle()
        self.assertEqual(self.test_cards, self.deck.cards)
コード例 #5
0
class Game():

    def __init__(self):
        self.players = []
        self.deck = Deck()

    def create_players(self, name, seed=100):
        self.players.append(Player(name, seed))

    def shuffle_deck(self):
        self.deck.shuffle()

    def deal(self):
        for i in range(2):
            for player in self.players:
                player.receive_card(self.deck.pop())

    def get_chip_count(self):
        for player in self.players:
            print(player.get_name(), player.get_wallet())
コード例 #6
0
ファイル: shoe.py プロジェクト: maggiemagnuson/War
class Shoe:

    def __init__(self, no_decks):
        self.shoe = Deck(no_decks)
        self._cards = queue.Queue(maxsize=52 * no_decks)
        self.shuffle()
        self._add_cards(self.shoe.deck)

    def shuffle(self):
        self.shoe.shuffle()

    def get_queue_size(self):
        return self._cards.qsize()

    def get_card(self):
        card = self._cards.get()
        return card

    def _add_cards(self, cards):
        for card in cards:
            self._cards.put(card)
コード例 #7
0
ファイル: test_deck.py プロジェクト: maggiemagnuson/War
class TestDeck(unittest.TestCase):
    def setUp(self):
        print("running setup")
        self.deck = Deck()

    def test_deck_length(self):
        self.assertEqual(len(self.deck.deck), 52)

    def test_suit_length(self):
        result = 0
        for card in self.deck.deck:
            if card.suit == "Hearts":
                result += 1
        self.assertEqual(result, 13)

    def test_shuffle(self):
        not_expected = self.deck.deck
        print("NOT EXPECTED")
        print(not_expected)
        self.deck.shuffle()
        print("AFTER SHUFFLE")
        print(self.deck.deck)
        self.assertEqual(len(self.deck.deck), 52)
        self.assertNotEqual(not_expected, self.deck.deck)
コード例 #8
0
ファイル: blackjack.py プロジェクト: jakersmith/Blackjack_py
class Blackjack:
    def __init__(self):
        self.__hands = [[], []]
        self.__account = 100
        self.__bet = self.__account + 1
        self.__playerValue = 0
        self.__dealerValue = 0
        self.__deck = Deck()

    def playGame(self):
        user = "******"
        while self.__account > 0 and user == "y":
            # Resetting values and lists for each game
            self.__playerValue = 0
            self.__dealerValue = 0
            self.__bet = self.__account + 1
            self.__hands[0] = []
            self.__hands[1] = []

            self.__betting()
            self.__dealCards()
            self.__playerTurn()
            if self.__playerValue <= 21:
                self.__dealerTurn()
            if self.__playerValue <= 21 and self.__dealerValue <= 21:
                self.__determineWinner()
            if self.__account > 0:
                print("Your account balance is $", self.__account)
                user = str.lower(
                    input("Would you like to play again? (Y or N) "))
                if user != "y":
                    break
        print("Thank you for playing!")
        print("Final balance = $", self.__account)

    def __betting(self):
        print("Your current balance is $", self.__account)
        if self.__account >= 5:
            while self.__bet > self.__account or self.__bet < 5:
                self.__bet = int(
                    input(
                        "Your bet must be between $5 and your account balance.\nHow much would you like"
                        " to bet? "))
        else:
            print("The your bet is ", self.__account)
            self.__bet = self.__account

    def __dealCards(self):
        self.__deck.shuffle()
        for i in range(2):
            self.__hands[0].append(self.__deck.draw())
            self.__hands[1].append(self.__deck.draw())
        print("The dealers second card is: ", self.__hands[1][1], '\n')

    def __playerTurn(self):
        print("Your Hand:", '\n', self.__hands[0][0], '\n', self.__hands[0][1],
              '\n')
        self.__getPlayerValue()
        hit = ""
        while hit == "":
            hit = str(input("Press ENTER to hit or type anything to stay"))
            print('\n')
            if hit == "":
                self.__hands[0].append(self.__deck.draw())
                self.__playerValue += self.__hands[0][len(self.__hands[0]) -
                                                      1].getCardValue()
            if self.__playerValue <= 21:
                print("Your Hand:")
                for i in range(len(self.__hands[0])):
                    print(self.__hands[0][i])
                print('\n')
            else:
                print("You bust!", '\n')
                print("Your Hand:")
                for i in range(len(self.__hands[0])):
                    print(self.__hands[0][i])
                print('\n')
                self.__account -= self.__bet
                break

    def __dealerTurn(self):
        self.__dealerValue = 0
        print("Dealer's Hand:")
        print(self.__hands[1][0])
        print(self.__hands[1][1], '\n')
        self.__getDealerValue()
        while self.__dealerValue < 17:
            print("Dealer takes a card")
            time.sleep(1)
            self.__hands[1].append(self.__deck.draw())
            self.__dealerValue += self.__hands[1][len(self.__hands[1]) -
                                                  1].getCardValue()
        if self.__dealerValue <= 21:
            print("Dealer holds", '\n')
        else:
            print("Dealer busts", '\n')
            self.__account += self.__bet

    def __determineWinner(self):
        print("Dealer's Hand:")
        for i in range(len(self.__hands[1])):
            print(self.__hands[1][i])
        print('\n')
        if self.__playerValue > self.__dealerValue:
            print("You win!")
            print('\n')
            self.__account += self.__bet
        elif self.__playerValue == self.__dealerValue:
            print("It's a tie!")
            print('\n')
        elif self.__playerValue < self.__dealerValue:
            print("You lost!")
            print('\n')
            self.__account -= self.__bet

    def __playAgain(self):
        print("Your account balance is $", self.__account)
        if self.__account > 0:
            user = str.lower("Would you like to play again? (Y or N)")
            if user != "y":
                print("Thank you for playing!")
                print("Final balance = $", self.__account)

    def __getPlayerValue(self):
        for i in range(len(self.__hands[0])):
            self.__playerValue += self.__hands[0][i].getCardValue()
        return self.__playerValue

    def __getDealerValue(self):
        for i in range(len(self.__hands[1])):
            self.__dealerValue += self.__hands[1][i].getCardValue()
        return self.__dealerValue
コード例 #9
0
def startGame(players):
    deck = Deck()
    scores = [0, 0, 0, 0]

    for handCount in range(1, 26):
        hand = handCount if handCount < 14 else 26 - handCount
        leading = hand % 4
        won = leading

        #Shuffle the deck
        deck.shuffle()

        #Deal the cards
        for dealing in range(hand):
            for player in players:
                player.deal(deck, deck.cards[0])

        #Display scores
        clear()
        for i in range(4):
            cols = [
                Fore.GREEN, Fore.LIGHTGREEN_EX, Fore.LIGHTYELLOW_EX,
                Fore.YELLOW
            ]
            print(cols[i] + players[i].name + ": " + str(scores[i]), end=" ")
        print(Style.RESET_ALL + "")

        #Determine trump suit
        trump = deck.getTrump()
        fores = [Fore.RED, Fore.BLACK]
        if SHOWOUTPUT:
            print("\nTrump is " + fores[SUITS.index(trump) % 2] + Back.WHITE +
                  trump + " " + Style.RESET_ALL)

        #Make bets
        bets = []
        tricks = [0, 0, 0, 0]
        if SHOWOUTPUT: print("\n" + players[leading].name + " leads\n")

        for player in players:
            i = players.index(player)
            if isinstance(player, Bot):
                bets.append(player.bet(hand - 1, trump, i == 0))
            else:
                bets.append(player.bet())

        for player in players:
            if SHOWOUTPUT:
                print(player.name + " bets " +
                      str(bets[players.index(player)]),
                      end="   ")

        if SHOWOUTPUT: print("\n")

        #Play hand
        for trick in range(hand):
            table = []
            for i in range(4):
                index = (i + won) % 4
                played = players[index].play(table, trump, 0, bets[index])
                players[index].hand.remove(played)
                table.append(played)
                if SHOWOUTPUT:
                    print(players[index].name + " plays " + str(played))

            winner = (getWinner(table, trump) + won) % 4
            if SHOWOUTPUT: print("\n" + players[winner].name + " wins\n")
            won = winner
            tricks[winner] += 1

            #Cleanup table, cards go back to deck
            while len(table) > 0:
                deck.cards.append(table[0])
                table.remove(table[0])

        for i in range(4):
            scores[i] += tricks[i]
            if tricks[i] == bets[i]: scores[i] += 5

        input("Press Enter to continue to next hand")
コード例 #10
0
def main(iterations=1):
    running_count = 0
    running_warrior1_wins = 0
    running_warrior2_wins = 0
    running_warrior1_game_wins = 0
    running_warrior2_game_wins = 0

    for i in range(0, iterations):
        warrior1 = Warrior()
        warrior2 = Warrior()

        deck = Deck()
        deck.shuffle()
        deck.shuffle()

        ####################
        # Deal out hands
        ####################
        i = 0
        for card in deck.deck:
            if i % 2 == 0:
                warrior1.add_cards([card])
            else:
                warrior2.add_cards([card])
            i += 1

        ####################
        # Play the game
        ####################
        count = 0
        warrior1_wins = 0
        warrior2_wins = 0
        warrior1_game_wins = 0
        warrior2_game_wins = 0
        while True:

            if int(warrior1.get_queue_size()) == 0:
                print("WINNER Warrior 2")
                warrior2_game_wins += 1
                break

            if int(warrior2.get_queue_size()) == 0:
                print("WINNER Warrior 1")
                warrior1_game_wins += 1
                break

            cards = None

            war1_card = warrior1.get_card()
            # print(war1_card)
            war2_card = warrior2.get_card()
            cards = [war1_card, war2_card]
            # print(war2_card)

            print(
                f"warrior1 [{war1_card.name}-{war1_card.suit}-{war1_card.power}]"
                f" warrior2 [{war2_card.name}-{war2_card.suit}-{war2_card.power}]"
            )

            if war1_card.power > war2_card.power:
                print("Warrior 1 sweeps")
                warrior1_wins += 1
                warrior1.add_cards(cards)
            elif war1_card.power < war2_card.power:
                print("Warrior 2 sweeps")
                warrior2_wins += 1
                warrior2.add_cards(cards)
            else:
                print("WAR")
                while True:

                    warror1_len = int(warrior1.get_queue_size())
                    warrior2_len = int(warrior2.get_queue_size())

                    min_len = min(warror1_len, warrior2_len)

                    if min_len == 0:
                        if warror1_len == 0:
                            warrior2.add_cards(cards)
                            break
                        if warrior2_len == 0:
                            warrior1.add_cards(cards)
                            break

                    print(min_len)
                    if min_len > 3:
                        r = 3
                    elif min_len == 3:
                        r = 2
                    elif min_len == 2:
                        r = 1
                    else:
                        r = 0

                    for i in range(0, r):
                        cards.append(warrior1.get_card())
                        cards.append(warrior2.get_card())

                    war1_war = warrior1.get_card()
                    cards.append(war1_war)
                    war2_war = warrior2.get_card()
                    cards.append(war2_war)

                    if war1_war.power > war2_war.power:
                        print("Warrior 1 sweeps")
                        warrior1_wins += 1
                        warrior1.add_cards(cards)
                        break
                    elif war1_war.power < war2_war.power:
                        print("Warrior 2 sweeps")
                        warrior2_wins += 1
                        warrior2.add_cards(cards)
                        break
                    else:
                        print("WAR AGAIN")
            count += 1

            print(
                f"warrior1 hand: {warrior1.get_queue_size()} warrior2 hand: {warrior2.get_queue_size()}"
            )

            if int(warrior1.get_queue_size()) + int(
                    warrior2.get_queue_size()) != 52:
                print("Invalid deck size")
                break

        warrior1_list = warrior1.queue_to_list()
        warrior2_list = warrior2.queue_to_list()
        warrior1_list.sort(key=lambda x: x.power, reverse=True)
        warrior2_list.sort(key=lambda x: x.power, reverse=True)

        if len(warrior1_list) != 0:
            for item in warrior1_list:
                print(item)

        if len(warrior2_list) != 0:
            for item in warrior1_list:
                print(item)

        print("------------------------------------------------")
        print(f"Iterations: {count}")
        print(f"Warrior1 Wins: {warrior1_wins}")
        print(f"Warrior2 Wins: {warrior2_wins}")
        print("------------------------------------------------")

        running_count += count
        running_warrior1_wins += warrior1_wins
        running_warrior2_wins += warrior2_wins
        running_warrior1_game_wins += warrior1_game_wins
        running_warrior2_game_wins += warrior2_game_wins

    print("*********************************************************")
    print(f"Total iterations: {running_count}")
    print(f"Total Warrior1 Game Wins: {running_warrior1_game_wins}")
    print(f"Total Warrior2 Game Wins: {running_warrior2_game_wins}")
    print(f"Total Warrior1 Wins: {running_warrior1_wins}")
    print(f"Total Warrior2 Wins: {running_warrior2_wins}")
    print("*********************************************************")