# 《零基础入门学习python》第38讲课后作业:德州扑克
import random as r
class Poker:
def __init__(self):
# 52张牌组成的列表(大小王除外)
self.poker = ["♠ 2", "♠ 3", "♠ 4", "♠ 5", "♠ 6", "♠ 7", "♠ 8", "♠ 9",
"♠ 10", "♠ J", "♠ Q", "♠ K", "♠ A",
"♥ 2", "♥ 3", "♥ 4", "♥ 5", "♥ 6", "♥ 7", "♥ 8", "♥ 9",
"♥ 10", "♥ J", "♥ Q", "♥ K", "♥ A",
"♣ 2", "♣ 3", "♣ 4", "♣ 5", "♣ 6", "♣ 7", "♣ 8", "♣ 9",
"♣ 10", "♣ J", "♣ Q", "♣ K", "♣ A",
"♦ 2", "♦ 3", "♦ 4", "♦ 5", "♦ 6", "♦ 7", "♦ 8", "♦ 9",
"♦ 10", "♦ J", "♦ Q", "♦ K", "♦ A"
]
"""
洗牌方法(Fisher-Yates费雪耶兹算法):在0 ~ N之间随机一个整数 i,交换self.poker[i]的牌和最后一张牌的位置;
下一次在 0 ~ N-1之间随机一个整数 i,将self.poker[i]与最后一张牌交换位置,依此类推直到最后一张牌;
从而打乱牌序
"""
def shuffle(self):
# 有多少张牌就循环多少次
loop = len(self.poker)
spot = 1
while loop:
# 随机位置的牌始终与最后的牌做位置交换,直到循环结束。
i = r.randint(0, len(self.poker) - spot)
self.poker[i], self.poker[
len(self.poker) - 1] = self.poker[
len(self.poker) - 1], self.poker[i]
loop -= 1
spot += 1
return self.poker[:]
# 发牌方法:先发给电脑,然后发给你,再发公开牌,牌会按照按花色按大小排序
def deal(self):
poker = Poker()
chaos = poker.shuffle()
computer = []
your = []
opencard = []
loop = 5
while loop:
computer.append(chaos.pop())
your.append(chaos.pop())
opencard.append(chaos.pop())
loop -= 1
print("电脑牌 ", computer)
print("你的牌 ", your)
print("组合牌 ", opencard)
p = Poker()
p.deal()