python扑克牌游戏
时间: 2023-09-21 20:03:22 浏览: 162
好的,我可以给你提供一个简单的Python扑克牌游戏的代码示例:
```python
import random
# 定义扑克牌花色和点数
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
# 定义Card类
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank} of {self.suit}"
# 定义Deck类
class Deck:
def __init__(self):
self.cards = []
for suit in suits:
for rank in ranks:
card = Card(suit, rank)
self.cards.append(card)
def shuffle(self):
random.shuffle(self.cards)
def deal_one(self):
if len(self.cards) > 0:
return self.cards.pop(0)
else:
return None
# 定义Game类
class Game:
def __init__(self):
self.deck = Deck()
self.deck.shuffle()
self.player_cards = []
self.dealer_cards = []
self.player_score = 0
self.dealer_score = 0
def deal_cards(self):
for i in range(2):
self.player_cards.append(self.deck.deal_one())
self.dealer_cards.append(self.deck.deal_one())
def get_score(self, cards):
score = 0
ace_count = 0
for card in cards:
if card.rank == 'Ace':
ace_count += 1
score += 11
elif card.rank in ['Jack', 'Queen', 'King']:
score += 10
else:
score += int(card.rank)
while ace_count > 0 and score > 21:
score -= 10
ace_count -= 1
return score
def get_player_score(self):
self.player_score = self.get_score(self.player_cards)
def get_dealer_score(self):
self.dealer_score = self.get_score(self.dealer_cards)
def hit(self):
self.player_cards.append(self.deck.deal_one())
def is_game_over(self):
if self.player_score > 21 or self.dealer_score > 21:
return True
elif len(self.player_cards) == 5 or len(self.dealer_cards) == 5:
return True
else:
return False
def get_winner(self):
if self.player_score > 21:
return 'Dealer'
elif self.dealer_score > 21:
return 'Player'
elif self.player_score > self.dealer_score:
return 'Player'
elif self.dealer_score > self.player_score:
return 'Dealer'
else:
return 'Tie'
def play(self):
self.deal_cards()
self.get_player_score()
self.get_dealer_score()
while not self.is_game_over():
print(f"Player's cards: {', '.join(str(card) for card in self.player_cards)}")
print(f"Player's score: {self.player_score}")
print(f"Dealer's cards: {str(self.dealer_cards[0])}")
action = input("Do you want to hit or stand? ")
if action == 'hit':
self.hit()
self.get_player_score()
else:
break
while self.dealer_score < 17:
self.dealer_cards.append(self.deck.deal_one())
self.get_dealer_score()
print(f"Player's cards: {', '.join(str(card) for card in self.player_cards)}")
print(f"Player's score: {self.player_score}")
print(f"Dealer's cards: {', '.join(str(card) for card in self.dealer_cards)}")
print(f"Dealer's score: {self.dealer_score}")
winner = self.get_winner()
print(f"The winner is {winner}!")
# 运行游戏
game = Game()
game.play()
```
这个游戏是一个简单的21点游戏,可以通过输入`hit`来继续抽牌,输入`stand`来停止抽牌。希望能帮到你!
阅读全文