#创作计划#生成一副牌
2024-12-20 06:38:42
发布于:北京
前言:这是一段生成扑克牌的教学,用Python进行实现
我们要生成一副扑克牌,目标结果如下(仅为示例):
player1's poker:
0.♠ 5 1.Joker - 2.♥ 3 3.♦ 4 4.♥ 10 5.♥ 9 6.♥ 4 7.♣ 4 8.♥ Q 9.♣ 10 10.♥ A 11.♥ 7 12.♦ 7 13.♣ A 14.♦ 9 15.♣ 9 16.♣ 6 17.♣ 3 18.♠ 7 19.♦ A 20.♦ Q 21.♥ K 22.♣ J 23.Joker + 24.♦ 8 25.♦ K 26.♣ K
player2's poker:
0.♠ 9 1.♥ 5 2.♣ 7 3.♣ 2 4.♠ J 5.♠ 10 6.♣ Q 7.♣ 8 8.♦ 5 9.♦ 3 10.♣ 5 11.♥ J 12.♥ 8 13.♠ K 14.♥ 6 15.♥ 2 16.♦ J 17.♠ 4 18.♠ A 19.♠ 6 20.♦ 2 21.♠ 8 22.♦ 6 23.♦ 10 24.♠ Q 25.♠ 2 26.♠ 3
正式教程:
1.首先定义存储牌的可迭代容器,这里使用列表:
all_poker = []
2.然后定义花色列表和数字列表:
num = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
suit = ["♦", "♣", "♥", "♠"]
3.接下来,推导式生成:
all_poker = [{"key": item1, "type": item2} for item1 in suit for item2 in num]
注意,这里每一副牌都是一个字典,例如♠ 5,就是{"key":"♠","type":"5"}
4.添加大小王:
all_poker.append({"key":"Joker","type":"+"})
all_poker.append({"key":"Joker","type":"-"})
5.使用random
库进行洗牌:
#第一行前加上这行代码
import random
random.shuffle(all_poker)
6.使用切片方法分出player1
和player2
两副牌:
p1 = all_poker[0:27]
p2 = all_poker[27:55]
7.格式化输出(重点):
如果你用的是VScode等强大一些的工具,那就请你照常格式化输出(高效版写法):
print("player1's poker:")
for i in p1:
print(f"{p1.index(i)}.{i['key']} {i['type']}", end=' ')
但大部分编辑器都会出现问题,请你这样写(兼容版写法):
print("player1's poker:")
for i in p1:
print("{}.{} {}".format(p1.index(i), i["key"], i["type"]), end=' ')
全部代码:
import random #导入random库
all_poker = [] #存储所有poker的列表
num = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] #所有数字
suit = ["♦", "♣", "♥", "♠"] #所有花色
all_poker = [{"key": item1, "type": item2} for item1 in suit for item2 in num] #推导式组成牌
all_poker.append({"key":"Joker","type":"+"})
all_poker.append({"key":"Joker","type":"-"})
random.shuffle(all_poker) #洗牌
print("player1's poker:")
for i in p1:
print("{}.{} {}".format(p1.index(i), i["key"], i["type"]), end=' ')
# 这是兼容版写法
for j in p2:
print(f"{p2.index(j)}.{j['key']} {j['type']}", end=' ')
# 这是高效版写法
想了解更多?点击这里!
有问题请点击这里提问或在下方留言~
全部评论 1
建议优化代码格式,变量命名
2024-12-20 来自 浙江
0
有帮助,赞一个