第五章:数学运算-random:伪随机数生成器-排列

5.3.6 排列
要模拟一个扑克牌游戏,需要把一副牌混起来,然后向玩家发牌,同一张牌不能多次使用,使用choice()可能导致同一张牌被发出两次,所以,可以使用shuffle()来洗牌然后在发各张牌时删除所发的牌。

import random
import itertools

FACE_CARDS = ('J','Q','K','A')
SUITS = ('H','D','C','S')

def new_deck():
    return [
        # Always use 2 places for the value,so the strings
        # are a consistent width.
        '{:>2}{}'.format(*c)
        for c in itertools.product(
            itertools.chain(range(2,11),FACE_CARDS),
            SUITS,
            )
        ]

def show_deck(deck):
    p_deck = deck[:]
    while p_deck:
        row = p_deck[:13]
        p_deck = p_deck[13:]
        for j in row:
            print(j,end=' ')
        print()

# Make a new deck,with the cards in order.
deck = new_deck()
print('Initial deck:')
show_deck(deck)

# Shuffle the deck to randomize the order.
random.shuffle(deck)
print('\nShuffled deck:')
show_deck(deck)

# Deal 4 hands of 5 cards each.
hands = [[],[],[],[]]

for i in range(5):
    for h in hands:
        h.append(deck.pop())

# Show the hands.
print('\nHands:')
for n,h in enumerate(hands):
    print('{}:'.format(n + 1),end=' ')
    for c in h:
        print(c,end=' ')
    print()

# Show the remaining deck.
print('\nRemaining deck:')
show_deck(deck)

这些扑克牌被表示为字符串,包括面值和一个表示花色的字母。要创建发出的“一手牌”,可以一次向4个列表分别增加一张牌,然后从这副牌中将发出的牌删除,使这些牌不会再次发出。
运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/88065579