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

时间:2009-05-24 09:30:51

标签: 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')

3 个答案:

答案 0 :(得分:5)

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

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

  • 使用

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

    而不是for-loop。

  • 使用enumerate,如下所示:

    for i, word in enumerate(wordlist)
    

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

  • 打开文件的默认模式为'r',无需指定。您是否使用codecs.open而不是内置open来获取Unicode字符串?另外,请尝试捕获Exception - 可能IOError的更具体的例外情况。

答案 1 :(得分:2)

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

答案 2 :(得分: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)
         ...