#
-*- coding: cp936 -*-
import
random
'''
方法1.使用random.shuffle进行洗牌
H:Hearts
S:Spade
C:Clubs
D:Diamonds
'''
suits
=
[
'
H
'
,
'
S
'
,
'
C
'
,
'
D
'
]
numbs
=
[
'
2
'
,
'
3
'
,
'
4
'
,
'
5
'
,
'
6
'
,
'
7
'
,
'
8
'
,
'
9
'
,
'
10
'
,
'
J
'
,
'
Q
'
,
'
K
'
,
'
A
'
]
jokers
=
[
'
BJ
'
,
'
RJ
'
]
cards
=
[]
#
生成2-A的所有牌
for
s
in
suits:
for
n
in
numbs:
cards.append(s
+
n)
#
生成二王
cards.extend(jokers)
print
cards
#
洗牌
random.shuffle(cards)
B1
=
[]
B2
=
[]
H1
=
[]
H2
=
[]
'''
取牌:
B1:使用索引为4的倍数
B2:使用余数为2的索引
H1:使用余数为1的索引
H2:使用余数为3的索引
'''
for
card
in
cards[:
-
6
]:
if
cards.index(card)
%
4
==
0:
B1.append(card)
elif
cards.index(card)
%
4
==
2
:
B2.append(card)
elif
cards.index(card)
%
4
==
1
:
H1.append(card)
else
:
H2.append(card)
#
打印洗牌结果
print
B1,len(B1)
print
B2,len(B2)
print
H1,len(H1)
print
H2,len(H2)
cards
=
[]
#
生成2-A的所有牌
for
s
in
suits:
for
n
in
numbs:
cards.append(s
+
n)
#
生成二王
cards.extend(jokers)
print
cards
B1
=
[]
B2
=
[]
H1
=
[]
H2
=
[]
'''
方法2:使用random.choice取牌
取牌:
共12此取牌,每轮B1,H1,B2,H2随机取牌,并从列表中删除,以后从剩余的牌中选取
'''
for
i
in
range(
12
):
card
=
random.choice(cards)
B1.append(card)
cards.remove(card)
card
=
random.choice(cards)
B2.append(card)
cards.remove(card)
card
=
random.choice(cards)
H1.append(card)
cards.remove(card)
card
=
random.choice(cards)
H2.append(card)
cards.remove(card)
#
打印取牌结果
print
B1,len(B1)
print
B2,len(B2)
print
H1,len(H1)
print
H2,len(H2)
本文介绍了一种使用Python的random模块实现的洗牌及分牌算法,通过两种不同的方式实现了扑克牌的洗牌过程,并按特定规则将牌分发给四家。第一种方法利用random.shuffle对牌堆进行打乱,第二种方法则通过random.choice随机抽取并移除的方式进行分牌。

1725

被折叠的 条评论
为什么被折叠?



