首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python简单Hangman游戏

Python简单Hangman游戏
EN

Code Review用户
提问于 2017-07-25 22:19:52
回答 1查看 10.3K关注 0票数 1

Q1。这段代码能简化/提高效率吗?

Q2。为什么必须以这样的方式缩进下面的代码?used.append(guess)so_far = new

Q3。出于兴趣,是否有一种方法只打印一次hangman图形,而只替换前面的数字,以避免在Python中大量的文本/重新加载?

下面的代码是从Python编程中为绝对初学者Hangman游戏稍微修改的。

代码语言:javascript
复制
#Python 3.4.3, MAC OSX (Latest)
#Hangman Game

import random
from time import sleep

HANGMAN = (
"""
 ------
 |    |
 |
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |   -+-
 | 
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-
 |   
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |   
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   | 
 |   | 
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   | |
 |   | |
 |  
----------
""")

WORDS = ("APPLE", "ORACLE", "MIMO", "TESLA")
word = random.choice(WORDS)
POSITIVE_SAYINGS = ("Well done!", "Awesome!", "You Legend!")
MAX_WRONG = len(word) - 1
so_far = ("-") * len(word)
used = []
wrong = 0

print("\t \t Welcome to Hangman!")
print()
input("Press Enter to START: ")

while wrong < MAX_WRONG and so_far != word:
    print()
    print(HANGMAN[wrong])
    print("Word so far: ", so_far)
    print("Letters used: ", used)

    guess = input("Guess a letter: ").upper()
    sleep(1) # Time delay - allows userfriendly reading
    print()

    while guess in used:
        print("Try again... You've already used this letter")
        guess = input("Guess a letter: ").upper()
        sleep(1)
        print()
    used.append(guess)

    if guess in word:
        print(random.choice(POSITIVE_SAYINGS),"...Updating word so far...")

        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess

            else:
                new += so_far[i]
        so_far = new 

    else:
        print("INCORRECT! Try again!")
        wrong += 1

print("Calculating result...")
sleep(1)
if wrong == MAX_WRONG:
    print("UNLUCKY! Better luck next time!")

else:
    print("WINNER! Congratulations!")

print()
print()
input("Press Enter to Leave: ")
EN

回答 1

Code Review用户

回答已采纳

发布于 2017-07-26 02:34:04

这看起来是个有趣的游戏!

到目前为止,它的结构很好,所以我有一些建议:

回答你的问题..。

Q1。这段代码能简化/提高效率吗?

是。为了简单起见,我建议把它放在一个类中。就效率而言,最大的运行时间是O(n),因此它已经是有效的。也许可以将其简化为允许最大运行时间为O(log ),但我不知道如何实现。

类版本:

代码语言:javascript
复制
# Whenever possible, only import specific functions from the library
from random import choice
from time import sleep


class Hangman:
    """
    A Hangman class.
    """
    _HANGMAN = (
        """
         ------
         |    |
         |
         |
         |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |
         |
         |
         |
         |
         |
        ----------
        """,
        """
         ------
         |    |
         |    O
         |   -+-
         | 
         |   
         |   
         |   
         |   
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-
         |   
         |   
         |   
         |   
         |   
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |   
         |   
         |   
         |   
         |   
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |    |
         |   
         |   
         |   
         |   
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |    |
         |    |
         |   | 
         |   | 
         |   
        ----------
        """,
        """
         ------
         |    |
         |    O
         |  /-+-/
         |    |
         |    |
         |   | |
         |   | |
         |  
        ----------
        """)

    _WORDS = ("APPLE", "ORACLE", "MIMO", "TESLA")
    _POSITIVE_SAYINGS = ("Well done!", "Awesome!", "You Legend!")

    def __init__(self):
        """
        The Python constructor for this class.
        """
        self._word = choice(self._WORDS)
        self._so_far = "-" * len(self._word)
        self._used = []
        self._wrong_answers = 0

    def play(self):
        """
        This is the main driver of the game.
        Plays the game.
        """
        self._reset_game()
        self._start_game()

        # The amount of incorrect answers should be no greater than the length
        # of HANGMAN.
        #
        # Use the length of HANGMAN to ensure there's no index
        # overflow error when printing current progress.
        while self._wrong_answers < len(self._HANGMAN) and self._so_far != self._word:
            self._print_current_progress()
            guess = self._user_guess()
            self._check_answer(guess)

        self._print_result()
        self._play_again()

    # ---------------------------------
    # "Private" methods

    def _check_answer(self, guess):
        """
        Checks to see if the user's guess is correct.
        :param guess: User's guess
        """
        if guess in self._word:
            print(choice(self._POSITIVE_SAYINGS), "...Updating word so far...")

            for i in range(len(self._word)):
                if guess == self._word[i]:
                    # so_far is spliced this way:
                    # so_far [from the start : up until, but not including the
                    #     position of the correctly guessed letter]
                    # + guessed letter
                    # + so_far [from the position next to the
                    #     correctly guessed letter : to the end]
                    self._so_far = self._so_far[:i] + guess + self._so_far[i+1:]

        else:
            print("INCORRECT! Try again!")
            self._wrong_answers += 1

    def _play_again(self):
        """
        Asks the user if he or she would like to play again.
        If the user wants to play again, calls play().
        Otherwise, thanks the user for playing.
        """

        print("Would you like to play again?")
        user_input = input("Enter Y for yes or N for no: ").upper()

        if user_input == "Y":
            self.play()

        else:
            print()
            print("Thank you for playing!")

    def _print_current_progress(self):
        """
        Prints the current progress of the game.
        """
        print()
        print(self._HANGMAN[self._wrong_answers])
        print("Word so far: ", self._so_far)
        print("Letters used: ", sorted(self._used))

    def _print_result(self):
        """
        Prints the result (win or lose).
        """
        sleep(1)
        print()
        print("Calculating result...")
        sleep(1)
        print()
        if self._wrong_answers == len(self._HANGMAN):
            print("UNLUCKY! Better luck next time!")
        else:
            print("WINNER! Congratulations!")

    def _reset_game(self):
        """
        Resets the game by calling the constructor.
        """
        self.__init__()

    def _start_game(self):
        """
        Starts the game by printing an introduction
        and asks the user to hit the ENTER key to continue.
        """
        print()
        print("\t\tWelcome to Hangman!")
        print()
        input("Press Enter to START:")

    def _user_guess(self):
        """
        Asks for the user to guess a letter.
        :returns: User's guessed letter.
        """
        guess = input("Guess a letter: ").upper()
        sleep(1)  # Time delay - allows user friendly reading
        print()

        while guess in self._used:
            print("Try again... You've already used this letter")
            guess = input("Guess a letter: ").upper()
            sleep(1)
            print()

        self._used.append(guess)

        return guess

if __name__ == '__main__':
    game = Hangman()

    game.play()

这在秘密要旨上也是可用的。

如果您只想专注于方法部分,可以单击“我的Github吉斯特链接”来查看方法版本。

Q2。为什么下面的代码必须以这样的方式缩进呢? used.append(guess) and so_far = new

从问题中的代码来看,used.append(guess)需要在while循环之外,否则,只要while条件为真,猜测的字母就会被反复添加到使用的列表中。

出于同样的原因,so_far = new需要在for循环之外。在我建议的代码中,您将不需要使用new变量,因为将使用字符串拼接。

Q3。出于兴趣,是否有一种方法只打印一次hangman图形,而只替换前面的数字,以避免在Python中大量的文本/重新加载?

目前我不知道。如果我有办法的话,我会把它记在心里,然后告诉你。

更新:

在下面的评论中,您问上面的代码是否是OOP。答案是不错的,但不是。我没有在单独的实体中定义模型或逻辑。但是,我确实创建了一个Gist链接,它是代码的OOP版本。

您可以单击这个Gist链接查看OOP版本。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

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

复制
相关文章

相似问题

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