|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 失败且常态 于 2022-11-30 17:36 编辑
设计一个 “斗地主” 的发牌程序
- import random
-
- cards = ["♦1", "♦2", "♦3", "♦4", "♦5", "♦6", "♦7", "♦8", "♦9", "♦10", "♦J", "♦Q", "♦K",
- "♥1", "♥2", "♥3", "♥4", "♥5", "♥6", "♥7", "♥8", "♥9", "♥10", "♥J", "♥Q", "♥K",
- "♣1", "♣2", "♣3", "♣4", "♣5", "♣6", "♣7", "♣8", "♣9", "♣10", "♣J", "♣Q", "♣K",
- "♠1", "♠2", "♠3", "♠4", "♠5", "♠6", "♠7", "♠8", "♠9", "♠10", "♠J", "♠Q", "♠K",
- "☀", "🌙"]
-
- def fy_shuffle(x, n=1):
- for i in range(n):
- target = list(x)
- result = []
- while target:
- r = random.randint(0, len(target)-1) # 步骤2
- result.append(target.pop(r)) # 步骤3
-
- return result
-
- def dealCards():
- a = input("请输入第一位游戏玩家名称:")
- b = input("请输入第二位游戏玩家名称:")
- c = input("请输入第三位游戏玩家名称:")
-
- r = {}
- r[a], r[b], r[c] = [], [], []
-
- new_cards = fy_shuffle(cards, 3)
-
- for i in range(17):
- r[a].append(new_cards.pop())
- r[b].append(new_cards.pop())
- r[c].append(new_cards.pop())
-
- d = random.sample((a, b, c), 1)[0]
- print(f"\n地主是:{d}\n")
- r[d].extend((new_cards.pop(), new_cards.pop(), new_cards.pop()))
-
- print(f"[{a}]拿到的牌是:{' '.join(r[a])}\n")
- print(f"[{b}]拿到的牌是:{' '.join(r[b])}\n")
- print(f"[{c}]拿到的牌是:{' '.join(r[c])}")
-
- dealCards()
复制代码
请问在这段代码中d = random.sample((a, b, c), 1)[0]这句代码后面的[0]是什么意思
还有为什么r[d].extend((new_cards.pop(), new_cards.pop(), new_cards.pop()))这句代码可以把地主的三张牌加进去,它给的不是一个新的键吗
Lists 的两个方法 extend 和 append 看起来类似,但实际上完全不同。extend 接受一个参数,这个参数总是一个 list,并且把这个 list 中的每个元素添加到原 list 中。
|
-
|