Python“Hangman”代码

时间:2018-02-09 11:36:33

标签: python arrays

我正在开发一个简单的基于文本的刽子手游戏(图形界面可能会在以后包括在内)并且有一个问题我无法克服,因为在您需要的单词中存在多个相同的字母猜测。

以下是我目前在我的代码中使用的内容,用于定义用户猜测单词中可能出现的字母的行为(通过函数guess())以及告诉用户他们的猜测是否正确的代码或不,或者如果他们已经猜到了那个词(函数猜测())。 [忽略令人困惑的函数/数组/变量名称,我有一个奇怪的命名系统,它们目前是占位符]

def guess():
    global letterGuess
    try:
        letterGuess = str(input("guess a letter: "))
        if len(letterGuess) > 1:
            print("only input one letter, please.")
            guess()
    except ValueError:
        print("you have inputted something other than a letter. please try again.")
        guess()
    letterGuess = letterGuess.lower()
    print("you guessed",letterGuess)


def guessing():
    global correctLetters
    global incorrectLetters
    global lives
    global letterGuess
    global word
    global guessyLetters
    print("")
    print("you have",lives,"lives and have",guessyLetters,"letters to guess.")
    print("correct letters guessed so far: ", correctLetters)
    print("incorrect letters guessed so far:", incorrectLetters)
    guess()
    time.sleep(0.5)
    print("")
    if letterGuess in word:
        if letterGuess in correctLetters:
            print("you have already guessed this letter.")
        else:
            print("you have guessed a letter correctly!")
            correctLetters.append(letterGuess)
            guessyLetters -= 1
    else:
        if letterGuess in incorrectLetters:
            print("you have already guessed this letter.")
        else:
            print("you have guessed incorrectly.")
            incorrectLetters.append(letterGuess)
            lives -= 1

比方说,例如,这个词是“兔子”,其中有两个b。 代码将接受“b”在单词“rabbit”中,但只接受其中一个b,现在意味着再次猜测b是不可能的,因为程序将返回“你已经猜到了这封信”。这使得游戏无法获胜,因为总会有剩余的第二个“B”你需要猜测。

或者,我试图创建一个while循环“while [letterGuess] in [word]”但是这只意味着,只要字母在单词中,那么用户需要猜出的字母数量继续消耗直到它变为0(几乎,循环意味着如果用户猜到一个正确的答案,那么他们会自动获胜)

我已经尝试通过将变量/单词的各个字母放入数组中来计算一种可能的方法来抵消这种情况,然后使用它来挑选数组中与用户猜测匹配的值。我还决定添加一个空格“”数组并打印出来,显示任何已经猜到正确替换空格的单词。 例如。: 这个词是:房子。 wordArray = ['h','o','u','s','e'],spaces = ['','','','',''](空格数对应于wordArray中的值的数量,如果猜到一个字母,则空格中的相应值将替换为字母)

我试图点击我想要尝试的简化版本:

split variable into separate letters
put separate letters into array
create array with same number of values marked "_"
if guess is in wordarray:
replace spaces[x] with wordarray[x]
for ALL spaces where wordarray[x] = guess

总结 - 如果我需要猜出单词“rabbit”中的字母并且我需要猜出字母B,那么我希望我的代码接受这封信作为正确的答案并且还将两个B标记为猜测而不是一。我建议这可以使用〜两个数组完成,但我不确定如何编写。任何人都可以提供任何写出来的方法吗?

2 个答案:

答案 0 :(得分:1)

这是一个如何使用我在评论中讨论的测试驱动开发方法(TDD)的示例。只是你的子弹列表的第一点。

word_to_guess = 'rabbit'

# How to store the letter of the word to guess in an array?

# Think of a test
# assertTrue(strToArray(word_to_guess), ['r', 'a', 'b', 'b', 'i', 't'])

# Now create the function
def strToArray(my_str):
  my_array = [letter for letter in my_str]
  return my_array

# Now make sure it passes.
if strToArray(word_to_guess) == ['r', 'a', 'b', 'b', 'i', 't']:
  print('that work')

# Now try to think of all edges cases. e.g   
# Ah... but now, we have duplicated 'b' letter, does it exists another datastructure to avoid have duplicated letters?
# Ah yes, I remember my CS classes! python's sets!

# Think of a test...

# Create the function.
def strToSets(my_str):
  my_set = set(my_str)
  return my_set

# Make sure it work...
if strToSets(word_to_guess) == set(['r', 'a', 'b', 'i', 't']):
  print('that work')


# But what if the word_to_guess have non-alphanumeric letters or uppercase letters?
# so forth and so on...

仅供参考,它存在方式更好方法在python中进行测试。这个例子只是为了让你有个主意,我个人使用Nosetests。 但是您可以根据自己的需要使用最好的工具。我建议Doctest开始(你在你的文档字符串中编写测试)。

希望它能以任何方式帮助你。

答案 1 :(得分:0)

你可以定义一个新函数,它接受猜测的字母和你正在尝试查找的单词,然后迭代它们。 每当字母是单词的一部分时,会增加一个计数器值,然后将其与您的密码的长度进行比较,如果isWordGuessed返回true,则表示他们已经猜到了该单词,否则该单词尚未被猜到

def isWordGuessed(secretWord, letterGuess):

# counter variable
guesses = 0

# go through each word in letterGuess 
for letter in letterGuess:

    # if the letter is in word increment guess by one
    if letter in word:
        guesses += 1
# compare guess counter with length of the word
if guesses == len(word):
    return True
else:
    return False