设计步骤
1.准备扑克牌图片
2.创建文件结构
3.编写代码实现功能
(1)导入必要的库
(2)创建一副牌
(3)发牌
(4)判断手牌等级
(5)确定胜者
(6)显示手牌
(7)主程序
(8)运行结果
完整代码
import random
from collections import Counter
from PIL import Image
import os
import matplotlib.pyplot as plt
from matplotlib import font_manager
def create_deck():
suits = ['Diamonds', 'Clubs', 'Hearts', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
return [(rank, suit) for suit in suits for rank in ranks], ranks
def deal_cards(deck):
random.shuffle(deck) # 洗牌
return deck[:3], deck[3:6] # A 得到前三张,B 得到后3张
def get_hand_rank(hand, ranks):
ranks_in_hand = [card[0] for card in hand]
suits = [card[1] for card in hand]
rank_count = Counter(ranks_in_hand)
unique_ranks = list(rank_count.keys())
is_flush = len(set(suits)) == 1 # 同花
is_straight = sorted(unique_ranks, key=lambda x: ranks.index(x)) == unique_ranks # 顺子
if is_flush and len(unique_ranks) == 3:
return (1, max(unique_ranks, key=lambda x: ranks.index(x))) # 同花
if is_straight:
return (2, max(unique_ranks, key=lambda x: ranks.index(x))) # 顺子
if 3 in rank_count.values():
return (3, max(unique_ranks, key=lambda x: ranks.index(x))) # 同点
if 2 in rank_count.values():
return (4, [r for r in unique_ranks if rank_count[r] == 2][0]) # 对子
return (5, max(unique_ranks, key=lambda x: ranks.index(x))) # 杂牌
def determine_winner(hand_a, hand_b, ranks):
rank_a = get_hand_rank(hand_a, ranks)
rank_b = get_hand_rank(hand_b, ranks)
if rank_a[0] < rank_b[0]:
return 'A' # A 胜
elif rank_a[0] > rank_b[0]:
return 'B' # B 胜
else: # Rank is the same
if ranks.index(rank_a[1]) > ranks.index(rank_b[1]):
return 'A'
elif ranks.index(rank_a[1]) < ranks.index(rank_b[1]):
return 'B'
else:
return 'Draw' # 平局
# 在一个窗口中显示两位玩家的手牌
def display_hands(hand_a, hand_b):
base_path = 'card_images/' # 设置图片文件夹路径
# 准备图片
images = []
for card in hand_a:
rank, suit = card
image_name = f"{rank}_of_{suit.lower()}.png"
image_path = os.path.join(base_path, image_name)
images.append(Image.open(image_path))
for card in hand_b:
rank, suit = card
image_name = f"{rank}_of_{suit.lower()}.png"
image_path = os.path.join(base_path, image_name)
images.append(Image.open(image_path))
# 使用 matplotlib 显示手牌
plt.figure(figsize=(10, 5))
for i, img in enumerate(images):
plt.subplot(1, 6, i + 1) # 1行6列的布局
plt.imshow(img)
plt.axis('off') # 关闭坐标轴
# 设置字体
font_path = 'C:/Windows/Fonts/simsun.ttc' # 根据需要调整路径
font_prop = (
font_manager.FontProperties(fname=font_path))
plt.title("玩家 A 的手牌 - 玩家 B 的手牌", fontsize=16, fontproperties=font_prop)
plt.show()
# 主程序
def simulate_single_game():
deck, ranks = create_deck()
hand_a, hand_b = deal_cards(deck)
winner = determine_winner(hand_a, hand_b, ranks)
return hand_a, hand_b, winner
# 进行一局游戏并输出结果
hand_a, hand_b, winner = simulate_single_game()
print("玩家 A 的手牌:", hand_a)
print("玩家 B 的手牌:", hand_b)
print("胜者:", winner)
# 显示手牌
display_hands(hand_a, hand_b)
请大家多多支持~~