首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python-3中的绞刑游戏

Python-3中的绞刑游戏
EN

Code Review用户
提问于 2020-10-29 00:43:32
回答 1查看 222关注 0票数 4
代码语言:javascript
复制
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()。我对蟒蛇还是很陌生的。

EN

回答 1

Code Review用户

发布于 2020-10-30 07:25:56

欢迎来到代码评审!

PEP-8

由于您对python还不熟悉,所以将窗口/选项卡打开到python中是个好主意。这主要是关于编码风格的建议。很少有东西可以从同样的东西中找到:

  • None这样的单例比较应该始终使用isis not,而不是相等的运算符。
  • 评论应该是完整的句子。第一个单词应该大写,除非它是以小写字母开头的标识符(永远不要更改标识符的大小写!)。
  • PEP 257描述了良好的docstring约定。请注意,最重要的是,结束多行docstring的"""本身应该位于一行上:

函数

正如您已经提到的那样,将代码拆分为单独的函数始终是一个很好的实践。

if __name__

将脚本的执行逻辑放在if __name__ == "__main__"块中。阅读更多关于为什么堆栈溢出的详细信息。

f-string

Python3.x还引入了文字字符串插值,或者更常用的术语:f- string 。阅读更多的关于这里(PEP-498)

型暗示

在编写函数时,还可以利用类型暗示向任何人提供更易读的代码流。这有助于消除不得不回溯变量类型等的体力劳动。更多的细节可以找到在PEP-484

博弈逻辑

presentation数组的初始化可以简化为:

代码语言:javascript
复制
presentation = ["_"] * len(answer)

对于用户的每个猜测字符,您都会一直在answer_list上循环,而不管是否验证猜测是否正确。

在对正确单词的每个字符进行循环之前,您已经设置了从未真正使用过的ind = 0

您的全局while循环依赖于条件completion == False (理想情况下应该是completion is False),但是在循环/条件之前,您确实有机会这样做,使变量无用。

重写

代码语言:javascript
复制
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()
票数 4
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/251281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档