Amazing-Python-Scripts

Форк
0
222 строки · 5.3 Кб
1
# IMPORT MODULES AND DEFINE VARIABLES
2

3
import random
4

5
playing = True
6

7

8
# CLASSES
9

10
class Card:  # Creates all the cards
11

12
    def __init__(self, suit, rank):
13
        self.suit = suit
14
        self.rank = rank
15

16
    def __str__(self):
17
        return self.rank + ' of ' + self.suit
18

19

20
class Deck:  # creates a deck of cards
21

22
    suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
23
    ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven',
24
             'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
25

26
    def __init__(self):
27
        self.deck = []  # haven't created a deck yet
28
        for suit in Deck.suits:
29
            for rank in Deck.ranks:
30
                self.deck.append(Card(suit, rank))
31

32
    def __str__(self):
33
        deck_comp = ''
34
        for card in self.deck:
35
            deck_comp += '\n ' + card.__str__()
36
        return 'The deck has: ' + deck_comp
37

38
    def shuffle(self):  # shuffle all the cards in the deck
39
        random.shuffle(self.deck)
40

41
    def deal(self):  # pick out a card from the deck
42
        single_card = self.deck.pop()
43
        return single_card
44

45

46
class Hand:   # show all the cards that the dealer and player have
47

48
    values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8,
49
              'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
50

51
    def __init__(self):
52
        self.cards = []
53
        self.value = 0
54
        self.aces = 0  # keep track of aces
55

56
    def add_card(self, card):  # add a card to the player's or dealer's hand
57
        self.cards.append(card)
58
        self.value += Hand.values[card.rank]
59
        if card.rank == 'Ace':
60
            self.aces += 1
61

62
    def adjust_for_ace(self):
63
        while self.value > 21 and self.aces:
64
            self.value -= 10
65
            self.aces -= 1
66

67

68
class Chips:   # keep track of chips
69

70
    def __init__(self):
71
        self.total = 100
72
        self.bet = 0
73

74
    def win_bet(self):
75
        self.total += self.bet
76

77
    def lose_bet(self):
78
        self.total -= self.bet
79

80

81
# FUNCTIONS
82

83
def take_bet(chips):  # ask for user's bet
84

85
    while True:
86
        try:
87
            chips.bet = int(input("How many chips would you like to bet? "))
88
        except ValueError:
89
            print("Sorry! Please can you type in a number: ")
90
        else:
91
            if chips.bet > chips.total:
92
                print("You bet can't exceed 100!")
93
            else:
94
                break
95

96

97
def hit(deck, hand):
98
    hand.add_card(deck.deal())
99
    hand.adjust_for_ace()
100

101

102
def hit_or_stand(deck, hand):   # hit or stand
103
    global playing
104

105
    while True:
106
        ask = input(
107
            "\nWould you like to hit or stand? Please enter 'h' or 's': ")
108

109
        if ask[0].lower() == 'h':
110
            hit(deck, hand)
111
        elif ask[0].lower() == 's':
112
            print("Player stands, Dealer is playing.")
113
            playing = False
114
        else:
115
            print("Sorry! I did not understand that! Please try again!")
116
            continue
117
        break
118

119

120
def show_some(player, dealer):
121
    print("\nDealer's Hand: ")
122
    print(" <card hidden>")
123
    print("", dealer.cards[1])
124
    print("\nPlayer's Hand: ", *player.cards, sep='\n ')
125

126

127
def show_all(player, dealer):
128
    print("\nDealer's Hand: ", *dealer.cards, sep='\n ')
129
    print("Dealer's Hand =", dealer.value)
130
    print("\nPlayer's Hand: ", *player.cards, sep='\n ')
131
    print("Player's Hand =", player.value)
132

133

134
# Game endings
135

136
def player_busts(player, dealer, chips):
137
    print("PLAYER BUSTS!")
138
    chips.lose_bet()
139

140

141
def player_wins(player, dealer, chips):
142
    print("PLAYER WINS!")
143
    chips.win_bet()
144

145

146
def dealer_busts(player, dealer, chips):
147
    print("DEALER BUSTS!")
148
    chips.win_bet()
149

150

151
def dealer_wins(player, dealer, chips):
152
    print("DEALER WINS!")
153
    chips.lose_bet()
154

155

156
def push(player, dealer):
157
    print("Its a push! Player and Dealer tie!")
158

159

160
# Gameplay!
161

162
while True:
163
    print("Welcome to BlackJack!")
164

165
    # create an shuffle deck
166
    deck = Deck()
167
    deck.shuffle()
168

169
    player_hand = Hand()
170
    player_hand.add_card(deck.deal())
171
    player_hand.add_card(deck.deal())
172

173
    dealer_hand = Hand()
174
    dealer_hand.add_card(deck.deal())
175
    dealer_hand.add_card(deck.deal())
176

177
    # set up the player's chips
178
    player_chips = Chips()
179

180
    # ask player for bet
181
    take_bet(player_chips)
182

183
    # show cards
184
    show_some(player_hand, dealer_hand)
185

186
    while playing:
187

188
        hit_or_stand(deck, player_hand)
189
        show_some(player_hand, dealer_hand)
190

191
        if player_hand.value > 21:
192
            player_busts(player_hand, dealer_hand, player_chips)
193
            break
194

195
    if player_hand.value <= 21:
196

197
        while dealer_hand.value < 17:
198
            hit(deck, dealer_hand)
199

200
        show_all(player_hand, dealer_hand)
201

202
        if dealer_hand.value > 21:
203
            dealer_busts(player_hand, dealer_hand, player_chips)
204

205
        elif dealer_hand.value > player_hand.value:
206
            dealer_wins(player_hand, dealer_hand, player_chips)
207

208
        elif dealer_hand.value < player_hand.value:
209
            player_wins(player_hand, dealer_hand, player_chips)
210

211
        if player_hand.value > 21:
212
            player_busts(player_hand, dealer_hand, player_chips)
213

214
    print("\nPlayer's winnings stand at", player_chips.total)
215

216
    new_game = input("\nWould you like to play again? Enter 'y' or 'n': ")
217
    if new_game[0].lower() == 'y':
218
        playing = True
219
        continue
220
    else:
221
        print("\nThanks for playing!")
222
        break
223

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.