用Python写一个纸牌游戏
时间: 2023-05-17 09:02:34 浏览: 89
好的,以下是一个简单的纸牌游戏的 Python 代码:
```python
import random
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank} of {self.suit}"
class Deck:
def __init__(self):
self.cards = []
for suit in ["Hearts", "Diamonds", "Clubs", "Spades"]:
for rank in range(1, 14):
self.cards.append(Card(suit, rank))
def shuffle(self):
random.shuffle(self.cards)
def deal(self):
return self.cards.pop()
class Player:
def __init__(self, name):
self.name = name
self.hand = []
def draw(self, deck):
self.hand.append(deck.deal())
def show_hand(self):
for card in self.hand:
print(card)
deck = Deck()
deck.shuffle()
player1 = Player("Player 1")
player2 = Player("Player 2")
for i in range(2):
player1.draw(deck)
player2.draw(deck)
print("Player 1's hand:")
player1.show_hand()
print("Player 2's hand:")
player2.show_hand()
```
这个代码实现了一个简单的纸牌游戏,包括了卡牌、牌堆、玩家等基本元素。你可以在此基础上进行扩展,添加更多的游戏规则和功能。
阅读全文