正在寻找改进我的刽子手代码的方法

Jus*_*ten 2 string file-io python-3.x

刚进入python,所以我决定做一个刽子手游戏.工作得很好,但我想知道是否有任何可以优化的方法或清理代码的方法.此外,如果有人可以推荐一个我可以做的项目那很酷.

import sys
import codecs
import random

def printInterface(lst, attempts):
    """ Prints user interface which includes:
            - hangman drawing
            - word updater """

    for update in lst:
        print (update, end = '')

    if attempts == 1:
        print ("\n\n\n\n\n\n\n\n\n\n\n\t\t    _____________")
    elif attempts == 2:
        print ("""          
                          |
                          | 
                          |
                          |
                          |
                          |
                          |
                          |
                          |
                    ______|______""")
    elif attempts == 3:
        print ("""
            ______          
                  |
                  | 
                  |
                  |
                  |
                  |
                  |
                  |
                  |
            ______|______""")
    elif attempts == 4:
        print ("""
            ______
           |      |
           |      | 
         (x_X)    |
                  |
                  |
                  |
                  |
                  |
                  |
            ______|______""")
    elif attempts == 5:
        print ("""
            ______
           |      |
           |      | 
         (x_X)    |
           |      |
           |      |
           |      |
                  |
                  |
                  |
            ______|______""")
    elif attempts == 6:
        print ("""
            ______
           |      |
           |      | 
         (x_X)    |
           |      |
          /|      |
           |      |
                  |
                  |
                  |
            ______|______""")
    elif attempts == 7:
        print ("""
            ______
           |      |
           |      | 
         (x_X)    |
           |      |
          /|\     |
           |      |
                  |
                  |
                  |
            ______|______""")
    elif attempts == 8:
        print ("""
            ______
           |      |
           |      | 
         (x_X)    |
           |      |
          /|\     |
           |      |
          /       |
                  |
                  |
            ______|______""")
    elif attempts == 9:
        print ("""
            ______
           |      |
           |      | 
         (x_X)    |
           |      |
          /|\     |
           |      |
          / \     |
                  |
                  |
            ______|______""")

def main():
    try:
        wordlist = codecs.open("words.txt", "r")
    except Exception as ex:
        print (ex)
        print ("\n**Could not open file!**\n")
        sys.exit(0)

    rand = random.randint(1,5)
    i = 0

    for word in wordlist:
        i+=1
        if i == rand:
            break
    word = word.strip()
    wordlist.close()

    lst = []
    for h in word:
        lst.append('_ ')

    attempts = 0    
    printInterface(lst,attempts) 

    while True:
        guess = input("Guess a letter: ").strip()

        i = 0
        for letters in lst:
            if guess not in word:
                print ("No '{0}' in the word, try again!".format(guess))
                attempts += 1
                break
            if guess in word[i] and lst[i] == "_ ":
                lst[i] = (guess + ' ')
            i+=1

        printInterface(lst,attempts)

        x = lst.count('_ ')
        if x == 0:
            print ("You win!")
            break
        elif attempts == 9:
            print ("You suck! You iz ded!")
            break

if __name__ == '__main__':
    while True:
        main()
        again = input("Would you like to play again? (y/n):  ").strip()
        if again.lower() == "n":
            sys.exit(1)
        print ('\n')
Run Code Online (Sandbox Code Playgroud)

Mar*_*ler 5

我没有尝试代码,但这里有一些随机提示:

  • 尝试将您的代码格式化为PEP 8(i += 1代替使用i+=1).PEP 8是Python的标准样式指南.

  • 使用

    lst = ['_ '] * len(word)
    
    Run Code Online (Sandbox Code Playgroud)

    而不是for循环.

  • 使用枚举如下:

    for i, word in enumerate(wordlist)
    
    Run Code Online (Sandbox Code Playgroud)

    而不是手动跟踪i循环.

  • 打开文件的默认模式是'r',不需要指定它.您是否使用codecs.open而不是内置open以获取Unicode字符串?此外,尝试捕捉一个更具体的例外Exception- 可能IOError.