如何动态获取一个函数到 运行 两次

How to get a function to run twice dynamically

这是一个函数。

def cut_dk():
    a = []; b = []
    random.shuffle(deck__)
    slice = deck__[:2]
    a.append(slice[0])
    b.append(slice[1])
    return a,b

c = cut_dk()
p1 = c[0]
p2 = c[1]

我在程序的顶部有这个功能以及其他功能。 它从预定义的列表中提取。 在程序中动态调用此函数时它returns相同的变量。 这是卡片组的切割(两张牌,最高的抽奖),当卡片相等时需要再次抽奖(这是问题,第二次抽奖),从列表中选择新的,但它只是重复它在内存中的变量。

在条件语句中再次调用函数只是 returns 在第一个 运行 上获取的相同初始变量,所以我无法在游戏过程中动态地重复剪切。

我会用 objectclass 来管理我的套牌。这将允许我们定义一个牌组,它被存储为一个对象并针对牌组执行多个功能,同时保留来自不同功能的状态变化。

class deck:
    """
        Class designed to manage deck including iterations of changes. 
        Shuffling the deck will retain shuffle changes 
    """
    def __init__(self):
        self.deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
        self.original = self.deck[:]

    def shuffle(self):
        """
           Shuffle deck in-place. self.deck will be modified
        """
        random.shuffle(self.deck)

    def cut(self):
        """
           Shuffles deck and draws the two top-most cards
           
           Returns: tuple(2) two cards from top of the deck
        """
        self.shuffle()
        a, b = self.deck[:2]
        return a, b

    def highest_draw(self):
        """
           Calls self.cut() to shuffle and retrieve 2x top-most cards. 

           If cards match the deck is shuffled and cut again.

           Returns: 2 Unique cards from top of the deck
        """
        a, b = self.cut()
        while a == b:
            a, b = self.cut()
        return a, b

    def reset(self):
        self.deck = self.original[:]

game = deck()
game.deck
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']

game.shuffle()
game.deck
#['A', 7, 5, 9, 8, 'J', 'K', 6, 4, 3, 1, 'Q', 2]

game.reset()
game.deck
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']

game.cut()
#('A', 'Q')

game.highest_draw()
#('J', 2)

您仍然需要定义如何确定“最高”牌,但这取决于您的套牌,您没有考虑这一点。

听起来生成器函数在这里很有用。您调用该函数一次以设置迭代器,然后从该迭代器调用 'draw' 卡片(在本例中,迭代器为 'cards')。请注意,您必须抓住 运行 整副牌并且整副牌都绑在一起的情况。我在其中添加了打印语句,以便更容易理解生成器的工作原理。

import random 

deck__ = list(range(3))*2

def draw_from_shuffled():
    random.shuffle(deck__)
    print(f'Deck after shuffling: {deck__}')
    for c in deck__:
        yield c

        
cards = draw_from_shuffled() #cards is now an iterator   
while True:
    try:
        a = next(cards)
        b = next(cards)
    except StopIteration:
        print(f'End of deck!')
        cards = draw_from_shuffled()
        continue
    print(f'Drew {a} and {b}')
    if a != b:
        break
print('Hand done.')

示例输出:

Deck after shuffling: [2, 2, 1, 1, 0, 0]
Drew 2 and 2
Drew 1 and 1
Drew 0 and 0
End of deck!
Deck after shuffling: [0, 0, 2, 2, 1, 1]
Drew 0 and 0
Drew 2 and 2
Drew 1 and 1
End of deck!
Deck after shuffling: [0, 2, 1, 0, 1, 2]
Drew 0 and 2
Hand done.

关于生成器的更多信息:https://realpython.com/introduction-to-python-generators/