answer = input("what's the word")
answer_list = list(answer) #list version of the original word
presentation = []
for i in range(len(answer_list)):
presentation.append("_") #makes a list that shows the progress of the player during the game
incorrect = 0 #number of allowed guesses
completion = False # condition for end game
while completion == False:
attempt = input('guess')
ind = 0 #index of the guess that appears in answer_list
count = 0 #number of occurences of the guess in answer_list
for x in answer_list: #searches for all occurences of the guess in answer_list and change presentation accordingly
if x == attempt:
num = answer_list.index(attempt)
presentation[num] = attempt
answer_list[num] = 0 #if there is an occurence, replace that occurence with 0 in answer_list
count += 1
if count>0:
print ("Your guess is correct, there was/were {} matches in the word".format(count))
print(presentation)
elif count == 0:
incorrect += 1
if incorrect == 5:
print("You lost")
break
if any(answer_list) == False: #since all 0 have a negative truthy value, we can use any() to check if any element has a truthy value
print("Congrats, you got everything correct")
completion = True
break我想要清理这个挂人游戏,并将其格式化为1或2个功能。我该怎么做呢?例如,初始化列表可以初始化(),从不正确的声明到代码的末尾可以是play_hangman()。我对蟒蛇还是很陌生的。
发布于 2020-10-30 07:25:56
欢迎来到代码评审!
由于您对python还不熟悉,所以将窗口/选项卡打开到python中是个好主意。这主要是关于编码风格的建议。很少有东西可以从同样的东西中找到:
None这样的单例比较应该始终使用is或is not,而不是相等的运算符。"""本身应该位于一行上:正如您已经提到的那样,将代码拆分为单独的函数始终是一个很好的实践。
if __name__块将脚本的执行逻辑放在if __name__ == "__main__"块中。阅读更多关于为什么堆栈溢出的详细信息。
Python3.x还引入了文字字符串插值,或者更常用的术语:f- string 。阅读更多的关于这里(PEP-498)。
在编写函数时,还可以利用类型暗示向任何人提供更易读的代码流。这有助于消除不得不回溯变量类型等的体力劳动。更多的细节可以找到在PEP-484。
presentation数组的初始化可以简化为:
presentation = ["_"] * len(answer)对于用户的每个猜测字符,您都会一直在answer_list上循环,而不管是否验证猜测是否正确。
在对正确单词的每个字符进行循环之前,您已经设置了从未真正使用过的ind = 0。
您的全局while循环依赖于条件completion == False (理想情况下应该是completion is False),但是在循环/条件之前,您确实有机会这样做,使变量无用。
from typing import List
MAX_ATTEMPTS: int = 5
def get_answer() -> str:
return input("What's the word? ")
def correct_guess(char_count: int, guessed_word: List[str]):
print(f"Your guess is correct, there was/were {char_count} matches in the word.")
print(" ".join(guessed_word))
def game_win(guessed_word: List[str]) -> bool:
return "_" in guessed_word
def game():
answer = get_answer()
correct_letters = set(answer)
guessed_word = ["_"] * len(answer)
incorrect = 0
while True:
if incorrect >= MAX_ATTEMPTS:
print("You lost!")
break
attempt = input("Guess: ")
if attempt not in correct_letters:
incorrect += 1
continue
char_count = 0
for index, char in enumerate(answer):
if char == attempt:
guessed_word[index] = char
char_count += 1
correct_guess(char_count, guessed_word)
if game_win(guessed_word):
print("Congrats, you got everything correct")
break
if __name__ == "__main__":
game()https://codereview.stackexchange.com/questions/251281
复制相似问题