python模拟斗地主发牌输出3个玩家的牌
时间: 2024-11-10 16:25:36 浏览: 18
在Python中模拟斗地主游戏的发牌过程,可以使用列表或者字典来表示每个玩家的牌。下面是一个简单的示例,展示如何给三个玩家随机分配牌:
```python
import random
# 初始化一副扑克牌
suits = ['♠', '♥', '♦', '♣']
ranks = list(range(2, 15)) + ['J', 'Q', 'K', 'A'] # 包含大小王
deck = [f'{rank}{suit}' for suit in suits for rank in ranks]
def deal_cards(num_players):
# 确保每名玩家的牌数相同
num_cards_per_player = len(deck) // num_players
cards_per_player = [num_cards_per_player] * num_players
# 如果剩余的牌不足以平均分,随机分配到第一个几个玩家
extra_cards = len(deck) % num_players
if extra_cards > 0:
cards_per_player[:extra_cards] += [num_cards_per_player + 1] * extra_cards
players = [[] for _ in range(num_players)]
# 随机打乱并分配牌
random.shuffle(deck)
for player_index, num_cards in enumerate(cards_per_player):
players[player_index] = deck[:num_cards]
deck = deck[num_cards:]
return players
# 输出3个玩家的牌
players = deal_cards(3)
for i, player in enumerate(players):
print(f"玩家{i+1}的牌:{player}")
阅读全文