如何重复一个函数,让它在每次重复时返回不同的值? (蟒蛇)

时间:2014-10-13 21:27:40

标签: python function repeat

我是新来的,这对我来说很难解释,所以请耐心等待,我会尽量具体说明!

我正在模拟顶级王牌的游戏,我已经定义了一个功能' playgame()'玩1场比赛。我需要玩大量的游戏(比方说,10000),但是我尝试过各种方式(即在for循环中,在while循环中,使用重复功能等),它只播放完全相同的游戏10000次。游戏的结果取决于牌组中的牌(在不同的功能中随机制作),但在每次重复时,它使用完全相同的牌组并在中处理牌完全相同的方式,所以每次结果都是一样的。

我想要发生的是,剧本要播放' 10000个不同的游戏,所以我可以从这些游戏中收集数据,而不是相同游戏的10000次重复(因为这是无用的信息)。

有没有办法重复你自己定义的函数,但每次都要使用不同的值?

这是我的功能:

def playgame():
    i=0
    a=0
    b=0
    while len(Player_0_Deck) and len(Player_1_Deck) >= 1:
        if len(Player_0_Deck) and len(Player_1_Deck) >= 1:
            Round_P0()
            a = a + 1
        if len(Player_0_Deck) and len(Player_1_Deck) >= 1:
            Round_P1()
            b = b + 1
        i = i + 1
        if i >= 100:
            break
    print a + b, "rounds have been played in this game."

Round_P0()和Round_P1()在这里定义:

def Round_P0():
a=1
Chosen0 = max(Player_0_Deck[0])
if Chosen0 is Player_0_Deck[0][0]:
    Matched1 = Player_1_Deck[0][0]
else:
    Matched1 = Player_1_Deck[0][1]
print "Player 0's chosen value:", Chosen0
print "Player 1's corresponding value:", Matched1
print "         "
if Matched1 <= Chosen0:
    Player_0_Deck.insert(len(Player_0_Deck)-1, Player_0_Deck.pop(0))
    Player_0_Deck.append(Player_1_Deck[0])
    Player_1_Deck.remove(Player_1_Deck[0])
    a = a + 1
if Matched1 > Chosen0:
    Player_1_Deck.insert(len(Player_1_Deck)-1, Player_1_Deck.pop(0))
    Player_1_Deck.append(Player_0_Deck[0])
    Player_0_Deck.remove(Player_0_Deck[0])
    a = a + 1
print Player_0_Deck
print Player_1_Deck

def Round_P1():
b=0
Chosen1 = max(Player_1_Deck[0])
if Chosen1 is Player_1_Deck[0][0]:
    Matched0 = Player_0_Deck[0][0]
else:
    Matched0 = Player_0_Deck[0][1]
print "Player 1's chosen value:", Chosen1
print "Player 0's corresponding value:", Matched0
print "             "
if Matched0 <= Chosen1:
    Player_1_Deck.insert(len(Player_1_Deck)-1, Player_1_Deck.pop(0))
    Player_1_Deck.append(Player_0_Deck[0])
    Player_0_Deck.remove(Player_0_Deck[0])
    b = b + 1
if Matched0 > Chosen1:
    Player_0_Deck.insert(len(Player_0_Deck)-1, Player_0_Deck.pop(0))
    Player_0_Deck.append(Player_1_Deck[0])
    Player_1_Deck.remove(Player_1_Deck[0])
    b = b + 1
print Player_0_Deck
print Player_1_Deck

如果需要,这就是我制作牌组/交易牌的方式:

N = int(raw_input("Choose the number of total cards you would like to play \
with. (It must be even.) "))

def MakeCard():
    A = random.randint(1,N)
    Yin = A
    Yang = N+1-A
    return (Yin, Yang)

def MakeDeck():
    return [MakeCard() for i in range(1,N+1)]

Deck = MakeDeck()

#Deal cards

random.shuffle(Deck)
print "This is the complete deck:", Deck
Player_0_Deck = Deck[0:N/2]
Player_1_Deck = Deck[N/2:N+1]
print "This is Player 0's hand:", Player_0_Deck
print "This is Player 1's hand:", Player_1_Deck

我希望这是有道理的,任何帮助都会受到赞赏!

1 个答案:

答案 0 :(得分:0)

deck对象在定义时传递给你的函数。它没有来回链接。将deck n作为参数传递,并为循环的每次迭代创建一个新的牌组,如

for _ in range(10000):
    theDeck = MakeDeck()
    playgame(theDeck)