2016-03-28 28 views
1

我想製作一個「終端黑客」遊戲,但我被困在某個地方。
這是我的代碼當前如下:生成一個列表的隨機排列

import random 

candidateWords = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER'] #etc, etc 

def wordlist(): 
    for index, item in enumerate(random.sample(list(candidateWords), 8)): 
     print(index, ") ", item, sep='')   
one = random.choice(candidateWords) 
print(one) 

print("Welcome to the Guess-The-Word Game.\nThe Password is one of these words:") 

我試圖做的8個字的清單,並列舉它給每一個字一個數字。然後,從8個單詞中,我需要隨機選擇一個單詞作爲答案,但我不知道如何。

我想使用random.sample()random.choice()

+0

注意:我忘了從wordlist()中取出(單詞)。請忽略:)和「one = random.choice(candidateWords)print(one)」部分完全是我想做我想做的事的猜測。它不起作用 – John

回答

1

random.sample()的第二個參數應該是< =第一個參數的長度,否則會產生異常。
代碼的其餘部分似乎很好。

import random 

candidateWords = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER'] 

candidateWordsShuffled = random.sample(candidateWords, min(len(candidateWords), 8)) 


def wordlist(): 
    for index, item in enumerate(candidateWordsShuffled): 
     print(index, ") ", item, sep='') 

one = random.choice(candidateWordsShuffled) 
print(one) 

print("Welcome to the Guess-The-Word Game.\nThe Password is one of these words:") 
wordlist() 
+0

謝謝你的回覆,但是現在它似乎是它唯一的一個印刷單詞,而不是其他8個單詞(因爲我需要印刷8個單詞中的8個隨機單詞+ 1個選擇的單詞。 ) – John

+0

嗯,'wordlist()'函數不打印隨機列表嗎? –

+0

噢,對不起,我忘了在最後粘貼wordlist()。但是它顯示了來自「候選詞」的100個單詞,你知道如何從中只找到8個單詞嗎?(我是否在for循環中鍵入8? – John