2

刚接触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')
4

3 回答 3

5

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

  • 尝试根据PEP 8格式化您的代码(使用i += 1而不是i+=1)。PEP 8 是 Python 的标准样式指南。

  • 采用

    lst = ['_ '] * len(word)
    

    而不是 for 循环。

  • 使用枚举,如:

    for i, word in enumerate(wordlist)
    

    i而不是在循环中手动跟踪。

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

于 2009-05-24T09:52:12.017 回答
2

我会在 printInterface 中使用 list 而不是 if .. else 语句。

于 2009-05-24T09:56:27.640 回答
2

第一个想法:ASCII艺术

Python 的特殊之处在于正则表达式语法和range()函数,以及[xxx for yyy in zzz]数组填充。

    import re

    def ascii_art(attempt):
        return re.sub(r'\d', '', re.sub('[0{0}].' \
            .format(''.join([str(e) for e in range(attempt + 1, 10)])), ' ', """
                3_3_3_3_3_3_
               4|      2|
               4|      2| 
             4(4x4_4X4)    2|
               5|      2|
              6/5|7\     2|
               5|      2|
              8/ 9\     2|
                      2|
                      2|
                1_1_1_1_1_1_1|1_1_1_1_1_1_
    """))

    for i in range(1, 10): 
        print(ascii_art(i)) 

第二个想法:循环

用于enumerate单词阅读循环。采用

for attempt in range(1, 10):
    # inside main loop
    ...
print ('you suck!')

作为主循环。操作员break应小心使用,而不是替代for

除非我错过了什么,否则结构

    for letters in lst:
        if guess not in word:
            ...
            break
        if guess in word[i]:
            ...

将更加透明

    if guess not in word:
             ...
    else:
         index = word.find (guess)
         ...
于 2009-06-10T02:25:17.660 回答