为了成为一名编程大师,我创建了一个简单的Hangman游戏,所以我想我会把它上传到这里,看看它是如何被改进的。
我的一个问题是使用异常处理。我试着在这里使用它,但我感觉到它可能是过分的。我应该只使用try/除非我知道会有异常,还是不管如何使用它们都是好的做法?
"""Hangman
Standard game of Hangman. A word is chosen at random from a list and the
user must guess the word letter by letter before running out of attempts."""
import random
def main():
welcome = ['Welcome to Hangman! A word will be chosen at random and',
'you must try to guess the word correctly letter by letter',
'before you run out of attempts. Good luck!'
]
for line in welcome:
print(line, sep='\n')
# setting up the play_again loop
play_again = True
while play_again:
# set up the game loop
words = ["hangman", "chairs", "backpack", "bodywash", "clothing",
"computer", "python", "program", "glasses", "sweatshirt",
"sweatpants", "mattress", "friends", "clocks", "biology",
"algebra", "suitcase", "knives", "ninjas", "shampoo"
]
chosen_word = random.choice(words).lower()
player_guess = None # will hold the players guess
guessed_letters = [] # a list of letters guessed so far
word_guessed = []
for letter in chosen_word:
word_guessed.append("-") # create an unguessed, blank version of the word
joined_word = None # joins the words in the list word_guessed
HANGMAN = (
"""
-----
| |
|
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| -+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| |
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| |
| |
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| | |
| |
|
--------
""",
"""
-----
| |
| 0
| /-+-\
| |
| |
| | |
| | |
|
--------
""")
print(HANGMAN[0])
attempts = len(HANGMAN) - 1
while (attempts != 0 and "-" in word_guessed):
print(("\nYou have {} attempts remaining").format(attempts))
joined_word = "".join(word_guessed)
print(joined_word)
try:
player_guess = str(input("\nPlease select a letter between A-Z" + "\n> ")).lower()
except: # check valid input
print("That is not valid input. Please try again.")
continue
else:
if not player_guess.isalpha(): # check the input is a letter. Also checks an input has been made.
print("That is not a letter. Please try again.")
continue
elif len(player_guess) > 1: # check the input is only one letter
print("That is more than one letter. Please try again.")
continue
elif player_guess in guessed_letters: # check it letter hasn't been guessed already
print("You have already guessed that letter. Please try again.")
continue
else:
pass
guessed_letters.append(player_guess)
for letter in range(len(chosen_word)):
if player_guess == chosen_word[letter]:
word_guessed[letter] = player_guess # replace all letters in the chosen word that match the players guess
if player_guess not in chosen_word:
attempts -= 1
print(HANGMAN[(len(HANGMAN) - 1) - attempts])
if "-" not in word_guessed: # no blanks remaining
print(("\nCongratulations! {} was the word").format(chosen_word))
else: # loop must have ended because attempts reached 0
print(("\nUnlucky! The word was {}.").format(chosen_word))
print("\nWould you like to play again?")
response = input("> ").lower()
if response not in ("yes", "y"):
play_again = False
if __name__ == "__main__":
main()发布于 2015-07-06 18:10:29
你有一个裸露的例外条款,即,
try:
some_code()
except:
clean_up()唯一的问题是它会捕获所有的异常,包括那些你真的不想忽视的异常(比如KeyboardInterrupt和SystemExit)。如果您的let块只捕捉到您期望的特定异常,并让所有其他异常正常地出现,情况会好得多。
关于您的代码的其他一些一般性评论:
play_again不同,您可以使用break语句。也就是说,将代码结构如下: True:#进行游戏,如果不是player_response_is_play_again():break,这会更干净,更容易理解,因为我不需要跟随play_again变量。发布于 2015-07-06 18:11:35
main函数中的代码太多了。试着看看是否可以将逻辑分离成不同的函数,每个函数都有各自的参数。例如,下面的代码块:
words = ["hangman", "chairs", "backpack", "bodywash", "clothing",
"computer", "python", "program", "glasses", "sweatshirt",
"sweatpants", "mattress", "friends", "clocks", "biology",
"algebra", "suitcase", "knives", "ninjas", "shampoo"
]
chosen_word = random.choice(words).lower()可以很容易地将其拆分为一个名为choose_word的函数,如下所示:
def choose_word(word_list):
"""
Choose a random word from the word_list
and return it.
"""
return random.choice(word_list)你也有一些长的细弦。例如,以下多行字符串:
"""
-----
| |
|
|
|
|
|
|
|
--------
"""可以很容易地缩短到这一点:
"-----\n| |\n|\n|\n|\n|\n|\n|\n|\n--------"请注意,这不是必需的。这只是个人喜好。
打印多个文本的方式也很奇怪。例如,下面的代码段:
welcome = ['Welcome to Hangman! A word will be chosen at random and',
'you must try to guess the word correctly letter by letter',
'before you run out of attempts. Good luck!'
]
for line in welcome:
print(line, sep='\n')可以将其再缩短为:
print(
"Welcome to Hangman! A word will be chosen at random and",
"you must try to guess the word correctly letter by letter",
"before you run out of attempts. Good luck!",
sep="\n"
)我还注意到,您正在混合使用单引号、''和双引号""。虽然这不是什么大问题,但我建议你选择一个或另一个,并坚持下去。
你成为设计师的方式也很奇怪。虽然它不是必需的,但我建议这样做:
my_list = [
value,
...
]最后,在获取用户输入时,不需要使用str函数将其转换为字符串。你可以这样做:user_input = input("prompt")。
发布于 2015-07-06 18:17:04
for line in welcome:
print(line, sep='\n')这类似于在一个函数中打印数组中多个字符串的代码类型。但是,由于数组中只有一条消息,这似乎有点过分,特别是因为只有三行。
只要打印出这样的信息就会容易得多:
print "..."
print "..."
...我建议您尝试以下三个选项之一,而不是试图获得自己的单词列表:
互联网上可能有大量的API,可以作为你程序的字典。
支持:您不必下载任何东西,只需简单地调用API即可。
Con: API有限制,比如每天的调用。另外,有时您的代码可能会挂在API调用上。
与Unix和Unix类似的操作系统一起出现的字典中的Unix单词。
它只是电脑上的一个文件,每行只有一个单词,所以很容易读懂。
您的用户可能不使用Unix或类似Unix的操作系统。
我不知道这件事。我看到它在一些Python代码中使用,在此之前涉及到一个英文单词引用,但我不知道如何访问它的内置字典工作。
chosen_word = random.choice(words).lower()调用方法.lower是没有意义的,因为字典中的所有单词都是小写的。
当询问用户是否想再次播放时:
print("\nWould you like to play again?")与其在后面检查两个选项(“是”和"y")时有一个条件,不如给用户他们的选项:
print("\nWould you like to play again? [Y/N]")此外,为了进一步消除额外的函数调用,将此消息放入input调用中:
input("\nWould you like to play again? [Y/N]\n>")代码开头的变量welcome:
welcome = ['Welcome to Hangman! A word will be chosen at random and',
'you must try to guess the word correctly letter by letter',
'before you run out of attempts. Good luck!'
]不应该在数组中;它应该在元组中,因为数组中的值不会改变。
words数组也是如此。
要回答您关于异常的问题,我认为只有当您知道会出现错误时,才应该使用try/exception。捕捉并停止错误总是很好的,但是如果没有错误,尝试是没有意义的。
另外,知道会有错误也会有所帮助,因为这样您就可以捕获正确的错误,而不仅仅是捕获Exception。
您在这里捕捉到的错误做得很好,并且区别于使用try/except和if/else:
try:
player_guess = str(input("\nPlease select a letter between A-Z" + "\n> ")).lower()
except: # check valid input
print("That is not valid input. Please try again.")
continue 但是,您应该捕捉到从该行中产生的错误类型。
我不确定哪个错误会出现,但我认为这要么是一个TypeError,要么是一个IOError。无论哪种方式,您都可以将try/except更改为如下所示:
try:
...
catch ExceptionType:
...https://codereview.stackexchange.com/questions/95997
复制相似问题