python hangman代码的属性错误问题

时间:2017-12-07 19:45:32

标签: python python-3.x attributeerror

我的python hangman代码有些麻烦,我似乎无法解决它。只是为了让每个人都知道我是编码的新手,我仍在学习如何做事。如果有人能帮助我,我将不胜感激。当我尝试从“打印...破折号”部分下面的while循环“追加”代码的任何其他部分时,我发现同样的情况。谢谢!

以下是代码:

import random

name = input("Hello, my name is H.A.N.K.M.A.N! What is yours?: ")
print("Hello, "+name," do you wanna play Hangman? Yes? Well why didn't you say so? Lets Goooooooo!")

def extractwords(filename,number):
    myfile=open(filename+".txt","r")
    details=myfile.readlines()
    myfile.close()
    words=[]
    for i in details:
        for item in i.split():
            letter=True
            for j in item:
                if j.isalpha()==False:
                    letter = False
            item = item.lower()
            if len(item)==number and letter==True and item not in words:
                    words.append(item)
    return words
player = "y"
while player =="y":
    complete=0
    guessed=[]
    errors=""
    characters = random.randint(5,9)
    tries = characters+3

    wordlist=extractwords("wordlist",characters)
    word=random.choice(wordlist)
    print("Testing word:",word)
    print("You have "+ str(tries)+" tries left")

    letters=[]
    for i in word:
        letters.append(i)

    hword=[]
    for i in range(0,characters):
        hword.append("-")

    dashes=""
    for i in hword:
        dashes = dashes+i

    print("The word you need to guess is ",dashes)
    while complete < characters and tries > 0:
        guess = input("Please input your letter: ")
        if guess in word:
            guessed.append(dashes)
            print("Noice job! You guessed the right letter!")
            tries=tries-1
            print("You have "+ str(tries)+" tries left")
            print(dashes)
            if len(guessed) == len(word):
                print("What? How did this happen? Yuu must have been cheating!Just Kidding! You did a good job on finding the word, so a GOOD JOB is in order!")
                layer = input("Would you like to play again? y/n: ")
        elif guess.isalpha and guess not in word:
            tries=tries-1
            print("I am sorry, but your guess is a number / not part of the word that I am thinking off. Please have another go!")
            errors.append(guess)
            print("The letters you entered so far:", errors)
            print("You have "+ str(tries)+" tries left")
        elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
            print("Please enter a valid/single letter.")
        elif guess in guessed:
            print("Please enter a letter that you havent entered previously. ")
        else:
            pass
    if tries==0:
        print("You lose!The word you were supposed to guess was ",word)
player = input("Would you like to play again? y/n: ")

`

1 个答案:

答案 0 :(得分:1)

好的,所以我查看了你的代码,你遇到了不止一个问题。 好的。你是新来的。无论如何,我将逐一介绍并为您描述它们,以及如何解决它们。好的,我们开始吧:

letters=[]
for i in word:
    letters.append(i)

这段代码虽然完美无缺,但却非常冗余。您只需使用letters = list(word)替换它。

hword=[]
for i in range(0,characters):
    hword.append("-")

dashes=""
for i in hword:
    dashes = dashes+i

这两个一起去。您可以将第一个替换为['-']*characters,将第二个替换为'-'*characters。请记住,当您将一个列表(在这种情况下,字符串是字符列表)乘以整数时,它会返回由原始列表的多次重复组成的列表。更节省空间......如果您先定义dashes,则可以使用hword = list(dashes)进行操作。

guessed.append(dashes)

我已经在评论中告诉过你这个,但我又回去了。 guessed应该使用guess值,而不是dashes值。

print(dashes)  #line 46

再次......你永远不会改变dashes,所以你不应该打印它。

elif guess.isalpha and guess not in word:
    tries=tries-1
    print("I am sorry, but your guess is a number / not part of the word that I am thinking off. Please have another go!")
    errors.append(guess)
    print("The letters you entered so far:", errors)
    print("You have "+ str(tries)+" tries left")
elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
    print("Please enter a valid/single letter.")
elif guess in guessed:
    print("Please enter a letter that you havent entered previously. ")
else:
    pass

在您检查guess是否在word之前,您应该可能检查它是否有效。这不仅仅是python,这通常是代码安全性。最基本的黑客攻击技术是输入如此大的输入,以便它进入内存的另一部分。这是不好的。 在你自己破坏之前检查自己。 我个人会这样做:

while ...
  #get input
  If not is_valid(your_input):
    continue
  #Do what you want with the input

你必须定义is_valid(),但这就是要点。这段代码很酷的部分是continue语句。 continue将循环循环回到开头。

if guess in word:
    guessed.append(guess)
    print("Noice job! You guessed the right letter!")
    tries=tries-1
    print("You have "+ str(tries)+" tries left")
    print(dashes)
    if len(guessed) == len(word):
        print("What? How did this happen? Yuu must have been cheating!Just Kidding! You did a good job on finding the word, so a GOOD JOB is in order!")
        layer = input("Would you like to play again? y/n: ")

好的,对于其中一个,您将player误称为layer。掖fypos。另一方面,您应该将语句从tries=...开始并以...dashes)结尾(第44-46行)移到if语句之外。也许在循环的最后设置它,以便在有有效输入的时候遇到它?

现在,我在您的代码中看到的最大错误:dashes。你继续使用它,但它总是有相同的价值。您需要在if guess in word:条件中添加一段代码,用新猜测更新hworddashes。这不是一项简单的任务,就像你的单词是bookkeeper一样,那么你不得不替换e一次,而是三次次。

elif len(guess)!=1 or "abcdefghiklmnoopqestuvwxyz":
    print("Please enter a valid/single letter.")

这一个......好的,所以我知道我已经查完了这段代码,但这有一个特别令人震惊的错误。 你不能说你的字母正确。带字母的部分小于没有。我假设您的意思是not guess in 'abcdefghijklmnopqrstuvwxyz',但由于您将第一部分排除在外,因此总是评估为True

player = input("Would you like to play again? y/n: ")

这是最后一个。缩进有问题。当你的游戏结束时,它永远不会被调用,因为它在主while循环之外。

话虽如此,你的代码也不错。这是我的修复:

import random

name = input("Hello, my name is H.A.N.K.M.A.N! What is yours?: ")
print("Hello, "+name," do you wanna play Hangman? Yes? Well why didn't you say so? Lets Goooooooo!")

def extractwords(filename,number):
    myfile=open(filename+".txt","r")
    details=myfile.readlines()
    myfile.close()
    words=[]
    for i in details:
        for item in i.split():
            letter=True
            for j in item:
                if j.isalpha()==False:
                    letter = False
            item = item.lower()
            if len(item)==number and letter==True and item not in words:
                    words.append(item)
    return words
player = "y"
while player =="y":
    complete=0
    guessed=""
    errors=""
    characters = random.randint(5,9)
    tries = characters+3

    wordlist=extractwords("wordlist",characters)
    word=random.choice(wordlist)
    print("Testing word:",word)
    print("You have "+ str(tries)+" tries left")

    letters = list(word)

    dashes = '-'*characters
    hword = list(dashes)
    print("The word you need to guess is ",dashes)
    while complete < characters and tries > 0:
        guess = input("Please input your letter: ")
        if not(guess.isalpha() or len(guess)==1):
          print('Error: invalid input.')
          continue
        if guess in word:
          if guess in guessed: 
            print("Already guessed that!")
            continue
          guessed += guess
          print("Guess correct!")
          #code to update dashes
          else:
          print('Incorrect guess.')
          errors += guess
        tries -= 1
        print("The letters you entered so far:", errors+guessed)
        print("You have "+ str(tries)+" tries left")
    if tries==0:
        print('lose')
    else:
     print('win')
    player = input("Would you like to play again? y/n: ")