关于在Python中制作Hangman游戏的建议?

时间:2014-02-25 00:15:54

标签: python

我目前正在使用Python创建一个刽子手游戏,但我无法弄清楚如何让它工作。在游戏中,有一个包含14个单词的列表,并且随机选择列表中的一个单词作为玩家必须猜测的单词。然后玩家必须继续输入字母,直到他们全部收到,或直到他们用尽猜测。在游戏开始时,将显示单词,每个字母由下划线表示。但我不知道如何让这些字母显示出来代替相应的下划线,因为玩家会猜到它们。这是我的基本设置:

print(stage1)
if (mystery == "spongebob" or mystery == "squidward" or mystery == "pineapple" or      mystery == "jellyfish"):
print("_ _ _ _ _ _ _ _ _")
print("Your word has 9 letters in it")
elif (mystery == "plankton"):
print("_ _ _ _ _ _ _ _")
print("Your word has 8 letters in it")
elif (mystery == "patrick"):
print("_ _ _ _ _ _ _")
print("Your word has 7 letters in it")
elif (mystery == "island"):
print("_ _ _ _ _ _")
print("Your word has 6 letters in it")
elif (mystery == "sandy" or mystery == "larry" or mystery == "beach"):
print("_ _ _ _ _")
print("Your word has 5 letters in it")
elif (mystery == "gary" or mystery == "tiki" or mystery == "rock" or mystery == "sand"):
print("_ _ _ _")
print("Your word has 4 letters in it")
print(mystery)

letter = str(input("Enter a letter you'd like to guess: "))

那么如何猜测下划线会被字母替换掉​​呢?

3 个答案:

答案 0 :(得分:1)

顺便说一句,不要继续为每个实例编写print语句,只需这样做:

>>> mystery = 'hippopotamus'
>>> print '_ '*len(mystery)
_ _ _ _ _ _ _ _ _ _ _ _ 

但是您还希望将下划线存储在变量中,以便以后可以更改和打印它们。所以这样做:

>>> mystery = 'hippopotamus'
>>> fake = '_ '*len(mystery)
>>> print fake
_ _ _ _ _ _ _ _ _ _ _ _ 

下一步是接受输入。在我看来,请勿使用str(input()),请使用raw_input。这只是一种习惯,因为如果您输入一个数字,它就会变为'1',而不是1

>>> guess = raw_input("Enter a letter you'd like to guess: ")
Enter a letter you'd like to guess: p

现在检查这封信是否在神秘之中。不要使用index来检查,因为如果有多个带有字母的实例,它将只迭代第一个实例。有关详细信息,请参阅this

>>> fake = list(fake)  #This will convert fake to a list, so that we can access and change it.
>>> for k in range(0, len(mystery)):  #For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
...    if guess == mystery[k]  #If the guess is in the answer, 
...        fake[k] = guess    #change the fake to represent that, EACH TIME IT OCCURS
>>> print ''.join(fake)  #converts from list to string
_ _ p p _ p _ _ _ _ _ _

答案 1 :(得分:1)

n="no"
while 'no':
    n = input("do you want to play? ")
    if n.strip() == 'yes':
        break

    """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 and your execution is complete.. no pressure'
               ]

    for line in welcome:
        print(line, sep='\n')



    play_again = True

    while play_again:


        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
        guessed_letters = [] 
        word_guessed = []
        for letter in chosen_word:
            word_guessed.append("-")
        joined_word = None

        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():
                    print("That is not a letter. Please try again.")
                    continue
                elif len(player_guess) > 1:
                    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

            if player_guess not in chosen_word:
                attempts -= 1
                print(HANGMAN[(len(HANGMAN) - 1) - attempts])

        if "-" not in word_guessed:
            print(("\nCongratulations! {} was the word").format(chosen_word))
        else:
            print(("Unlucky! The word was {}.").format(chosen_word))

        print("Would you like to play again?")

        response = input("> ").lower()
        if response not in ("yes", "y"):
            play_again = False

if __name__ == "__main__":
    main()

此代码播放刽子手游戏,尽管可以随意更改单词。我去年在学校用了很长时间来编写代码,这是我10年级评估的一部分。

喜欢玩刽子手。:)

获得一些代码的另一种方法是看看其他人。他们的代码可以为您提供一些灵感,您可以使用多个人的代码来创建程序。

答案 2 :(得分:0)

实际上,您可以执行此操作。

import random

print("Welcome to hangman!!")
words = []
with open('sowpods.txt', 'r') as f:
    line = f.readline().strip()
    words.append(line)
    while line:
        line = f.readline().strip()
        words.append(line)

random_index = random.randint(0, len(words))

word = words[random_index]
guessed = "_" * len(word)
word = list(word)
guessed = list(guessed)
lstGuessed = []
letter = input("guess letter: ")
while True:
    if letter.upper() in lstGuessed:
        letter = ''
        print("Already guessed!!")
    elif letter.upper() in word:
        index = word.index(letter.upper())
        guessed[index] = letter.upper()
        word[index] = '_'
    else:
        print(''.join(guessed))
        if letter is not '':
            lstGuessed.append(letter.upper())
        letter = input("guess letter: ")

    if '_' not in guessed:
        print("You won!!")
        break