2016-03-24 9 views
0

私はハングマンゲームを作っています。私が条件付きクラスとクラスを除いてコードを作ったとき、うまくいきました。基本的に私の問題は以下のコードになります:Python:コードは入力に応じて条件に違反します

  1. 文字 "t"のみが一致します。他の手紙と一致することはできません。

  2. 最初の試行で「t」と入力した場合、意図的に次の4つの文字が間違って取得されますが、7回転後まで終了しません。しかし、他の手紙を最初に入力した場合、それは4つの間違ったターンの後に終了するはずです。

私の質問 ....

  1. どのように私はそれがself.wordインデックスにある他の文字と一致させるために得ることができますか?

  2. 私が最初の試行で "t"を入力した後、他のすべての文字を間違えた場合、mainメソッドのwhileループで設定した条件に従わないのはなぜですか?絞首刑執行人のゲームで

    class Hang(): 
    
        def __init__(self): 
         self.turns = 0 
         self.word = ['t', 'h', 'i', 's'] 
         self.empty = ["__", "__", "__", "__"] 
         self.wrong = [] 
    
        def main(self): 
         while self.turns < 4: 
          for i in self.word: 
           choice = raw_input("Enter a letter a-z: ") 
           if choice == i: 
            index = self.word.index(i) 
            self.empty.pop(index) 
            self.empty.insert(index, i) 
            print self.empty 
           else: 
            print "Wrong" 
            self.wrong.append(choice) 
            print self.wrong 
            print self.empty 
            self.turns += 1 
    
    char1 = Hang() 
    char1.main() 
    

答えて

0

あなたは、任意の順序で句内の任意の文字を推測することができます。しかし、あなたは順番に各文字を通過するforループを使用していて、プレイヤーが正しくため

の文字が代わりに

while self.turns < 4: 

    choice = raw_input("Enter a letter a-z: ") 

    # optional, if user enters more than a single letter 
    if len(choice) > 1: 
     print "invalid choice" 
     continue     # loop again from start 

    index = self.word.index(choice) 

    if index != -1:  
     # -1 indicates character in not int the string 
     # so this block is only executed if character is 
     # in the string 

     self.empty[index] = choice  # no need to pop, you can simply change the value of the list at a given index 

    else: 
     print "wrong" 
     self.turns += 1 

    print self.empty 
+0

'指数= self.word.indexこれを試してみてください推測場合にのみ正しいです(i) 'index()メソッドのiはどこから来ますか? – staredecisis

+0

@staredecisisそれは申し訳ありません、インデックス(選択肢) – francium

関連する問題