2015-12-09 106 views
2

我沿着Yahtzee的骰子滾動遊戲創造線。我必須給用戶5個擲骰子,並詢問他們想要重擲哪個骰子的5位數字。對於實施例冷凍骰子滾動?

Your roll is: 5 1 5 5 1 
Which dice should I roll again?: 234 
Your new roll is: 5 7 2 4 1 

3箇中間號碼改變,因爲這些都是切塊軋製。 我不知道如何有效地做到這一點,我可以創建240條if語句,但似乎並不像這樣做的正確方法。

這是我的代碼迄今

import random 

def yahtzee(): 
    dice1 = random.randrange(1,6) 
    dice2 = random.randrange(1,6) 
    dice3 = random.randrange(1,6) 
    dice4 = random.randrange(1,6) 
    dice5 = random.randrange(1,6) 
    print('Your roll is: ' + ' ' + str(dice1) + ' ' + str(dice2) + ' ' + str(dice3) + ' ' + str(dice4) + ' ' + str(dice5)) 
    reroll = input('Which dice should I roll again?: ') 

這使我的結果:

yahtzee() 
Your roll is: 4 3 2 1 5 
Which dice should I roll again?: 

不知道如何去這樣做骰子rerolled,任何幫助,將不勝感激!謝謝!

回答

2

在一般情況下,它更容易管理存儲在列表中的結果:

def yahtzee(): 
    dice = [random.randrange(1, 6) for _ in range(5)] 
    print('Your roll is: ', *dice) 
    reroll = input('Which dice should I roll again?: ') 
    for i in reroll: 
     dice[int(i) - 1] = random.randrange(1, 6) 
    print('Your roll is: ', *dice) 

輸出示例:

Your roll is: 5 3 2 5 3 
Which dice should I roll again?: 12 
Your roll is: 1 2 2 5 3 
+0

啊真棒,太感謝你了,算了我的代碼是非常低效的,真的欣賞它! –