2016-11-15 25 views
0

所以我試圖做一個hang子手遊戲的練習。我已經寫了函數來獲取隨機詞和一個函數,將這些字符與索引進行配對。想知道用戶猜測一個正確的字符是否有引用字典的方法,並將字符輸出到正確索引處的空列表中?代碼我到目前爲止:字典密鑰:值刪除和重新插入列表或東西

import random 
import sys 

def hangman(): 
    print("Welcome to Hangman\n") 
    answer = input("Would you like to play? yes(y) or no(n)") 
    if answer is "y": 
     print("Generating Random Word...Complete") 
     wordlist = [] 
     with open('sowpods.txt', 'r') as f: 
      line = f.read() 
      line = list(line.splitlines()) 
      word = list(random.choice(line)) 
      Key = matchUp(word) 


    else: 
     sys.exit() 

def matchUp(word): 
    list = [] 
    for x in word: 
     list.append(word.index(x)) 
    newDict = {} 
    newDict = dict(zip(word, list)) 
    return newDict 

hangman() 
+0

你能提供邏輯,一步一步?引言詞很難理解。 –

+0

因此,我希望用戶猜測隨機生成的單詞中的一個字符。如果這個字符在單詞中,那麼我想要一個函數來引用我創建的字典,並使用字符及其索引將該字符添加到指定索引處的列表中,以便用戶可以看到他們正確猜測的位置。 –

回答

1

所以這樣?您可以跳過整個辭典的事情......

a = "_" * len(word) 

def letter_check(letter): 
    if letter in word: 
     a[word.index(letter)] = letter 
     # possibly print 'a' here 
    else: 
     # function for decrement tries here 

編輯:噢...我忘了潛在的重複字母......嗯......這個怎麼樣:

a = "_" * len(word) 

def letter_check(letter): 
    if letter in word: 
     for x, y in enumerate(word): 
      if letter == y: 
       a[x] = letter 
    else: 
     # function for decrement tries here 
+0

我犯了一些我現在已經修復的錯誤:P –

+0

a =「_」* len(word),這行是幹什麼的? –

+0

這是一個空白詞的表示形式,每個字母都帶有空格('_')。 (開始)編輯:希望是有道理的 –