允许最终用户输入单词集

时间:2014-04-05 00:24:06

标签: python

我一直在研究这个刽子手游戏,它目前运行良好。游戏使用程序中单词数组中的随机单词。我希望程序允许和最终用户输入一组新单词,如果他们愿意的话。但是,我不知道该怎么做;有任何想法吗? 这是目前的代码:

name=(input("Please enter your player name: "))
print("Hello " + name + " welcome to hangman!")
import random
score=6
HANGMANPICS = ['''
_______
  |   |
      |
      |
      |
      |
LIVES=6
''', '''
_______
  |   |
(°?°) |
      |
      |
      |
LIVES=5
''', '''
_______
  |   |
(°?°) |
  |   |
      |
      |
LIVES=4
''', '''
_______
  |   |
(°?°) |
  |-  |
      |
      |
LIVES=3
''', '''
_______
  |   |
(°?°) |
 -|-  |
      |
      |
LIVES=2
''', '''
_______
  |   |
(°?°) |
 -|-  |
 /    |
      |
LIVES=1
''', '''

_______
  |   |
(°?°) |
 -|-  |
 / \  |
      |
LVIES=0
''']
words = 'albania andorra armenia austria azerbaijan belarus belgium bulgaria croatia cyprus denmark england estonia finland france georgia germany greece hungary iceland ireland italy kosovo latvia liechtenstein lithuania luxembourg macedonia malta moldova monaco montenegro netherlands norway poland portugal romania russia serbia slovakia slovenia spain sweden switzerland turkey ukraine'.split()
def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()

    print('Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()

    blanks = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

    for letter in blanks: # show the secret word with spaces in between each letter
        print(letter, end=' ')
    print()

def getGuess(alreadyGuessed):
    # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
    while True:
        print('Guess a letter.')
        guess = input()
        guess = guess.lower()
        if len(guess) != 1:
            print('Please enter a single letter.')
        elif guess in alreadyGuessed:
            print('You have already guessed that letter. Choose again.')
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print('Please enter a LETTER.')
        else:
            return guess

def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')


print('H A N G M A N\nEuropean countries edition')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False

while True:
    displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)

    # Let the player type in a letter.
    guess = getGuess(missedLetters + correctLetters)

    if guess in secretWord:
        correctLetters = correctLetters + guess

        # Check if the player has won
        foundAllLetters = True
        for i in range(len(secretWord)):
            if secretWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if foundAllLetters:
            print('Yes! The secret word is "' + secretWord + '"! You have won!')
            print ("Your score was " + str(score) + "/6")
            score=6
            gameIsDone = True
    else:
        missedLetters = missedLetters + guess
        score=score-1
        # Check if player has guessed too many times and lost
        if len(missedLetters) == len(HANGMANPICS) - 1:
            displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
            print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
            gameIsDone = True
            print("Your score was " + str(score) + "/6\nBetter luck next time kid!;)")
            score=6

    # Ask the player if they want to play again (but only if the game is done).
    if gameIsDone:
        if playAgain():
            missedLetters = ''
            correctLetters = ''
            gameIsDone = False
            secretWord = getRandomWord(words)
        else:
            break

3 个答案:

答案 0 :(得分:0)

将输入的单词集转换为文件。您可能需要一个正则表达式来确保只允许有效的单词。

答案 1 :(得分:0)

这是一个可以帮助您入门的基本解决方案。

让用户在命令行输入文字文件:

python hangman.py file-with-words.txt

file-with-words.txt包含:

British Columbia,Alberta,Saskatchewan,Manitoba,Ontario,Quebec,Newfoundland,New Brunswick,Prince Edward Island,Nova Scotia,Nunavut,Yukon

在您的脚本中,打开并使用该文件:

words_file = open(sys.argv[1], 'r')
words = words_file.read().split(',')
words_file.close()
secretWord = getRandomWord(words)

进行一些错误处理并删除您可能遇到的任何新行,并且您已完成设置。

答案 2 :(得分:0)

>>> words = "Example Word List"
>>> words += " " + input("Add word to word list: ")
Add word to word list: Another
>>> print(words)
Example Word List Another

但是,我强烈建议您只使用变量类型list作为单词,而不是在一个以空格分隔的长字符串中包含单词列表。在这种情况下,它看起来像这样:

>>> words = ["Example","Word","List"]
>>> words.append(input("Add word to word list: "))
Add word to word list: Another
>>> print(words)
['Example', 'Word', 'List', 'Another']

但是使用此解决方案,您添加的单词仅在您的程序打开时才可用,如果您关闭游戏,则会丢失它们。更好的方法是将你的文字保存在一个文本文件中,这样如果你添加它们,你就会保留这些文字。