2013-05-08 83 views
0
def main(): 
    #word = input("Word to guess for player 2:") 
    word = ['h','e','l','l','o'] 
    word2 = "hello" 
    #make a list of _ the same length as the word 
    display =[] 
    for i in range (0,len(word)): 
     display.append("_") 

    chances = int(input("Number of chances to guess word:")) 
    if len(word)== 11: 
     print ("Your word is too long. It has to be 10 charecters or less") 
    else: 
     word = word 
    if chances < len(word): 
     answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word))) 
     if answer == "no": 
      chances= int(input("Number of chances:")) 
     else: 
      chances = chances 
      ("Ok then lets continue with the game") 
    print ("Player 2, you have {0} chances to guess the word.". format (chances)) 
    won = False 
    underscore = False 
    while chances > 0 and won == False and underscore == False: 
     guess = input("Enter your guess: ") 
     gC=False 

     for i in range (0,len(word)): 
      if guess == word[i]: 
       gC=True 
       display[i]=guess 

     if not gC: 
      chances = chances - 1 

     display2 = "" 
     for i in display: 
      display2 = display2 + i + " " 

由於某些原因,當我聲明我的while循環時,代碼不起作用,因爲遊戲繼續進行,直到用戶用完猜測' 。有沒有人有任何建議,我該如何解決這個問題?通過變量來檢查它是否不包含字符串

+0

使用'while while chances> 0而不是贏得和不下劃線;測試是否永遠不需要布爾型「== False」或「== True」。 – 2013-05-08 17:02:23

回答

2

當用戶通過猜測所有字母贏得遊戲時,您從未將won設置爲True。

+0

也強調從未設置爲真,不知道是什麼。 – VoronoiPotato 2013-05-08 16:58:41

+0

我忘了在我的程序中包含這段代碼:對於我在顯示中: 如果「_」不在顯示中: 下劃線=真 如果不是下劃線: won = True – thatcoolkid 2013-05-08 17:10:59

0

這不是你原來的問題的答案,而是更多的代碼審查,但也許你會發現它很有用。

word = list('hello') # replaces manual splitting of string into letters 

display = [ '_' ] * len(word) # replaces build-up using for-loop 

chances = input("Number ... ") # already returns int if the user enters an int 
           # but will evaluate any valid python expression the 
           # user enters; this is a security risk as what 
           # ever is done this way will be done using your 
           # permissions 
chances = int(raw_input("Number ...")) # probably what you wanted 

... 
else: 
    word = word # does nothing. remove this line and the "else:" above 

chances -= 1 # replaces 'chances = chances - 1' and does the same 

display2 = ' '.join(display) # replaces the for-loop to build display2 

此外,我建議使用更好的名稱。在這種情況下,諸如display2gC等變量沒有多大幫助。在專業編程中,你必須記住,你正在編寫你的代碼(也是,甚至主要)爲下一個必須維護它的開發者。因此,使其可讀性和可理解性。改爲選擇名稱,如displayStringguessedCorrectly

相關問題