子手游戏。如何切片字符串以更改原始值

时间:2018-08-27 23:38:52

标签: python string

我对python非常陌生,我正尝试制作一个子手游戏。 我想更改一个字符串以显示猜出的字母的数量,但是由于某些原因,我一直在得到奇怪的结果。这是我的代码:

import random
guesses_left = 9 
def show_guesses_left():
    print("You have", guesses_left, "guesses left")


wordlist = ['nerd', 'python', 'great', 'happy', 'programmer', 'long', 'short', 'stupid']
word = random.choice(wordlist)
wordwin = word
hidden_word = ["?" for q in word]
letters_guessed = ''.join(hidden_word)

print("Welcome to Hangman!!")
print("My word is", len(word), "letters long")
print(wordwin)
print(letters_guessed)


def request_guess():
    global guesses_left
    global word
    global letters_guessed
    x = input(f"What is your guess? \n{letters_guessed}")

    if x in word:
        print("Great you guessed a letter")
        t = word.find(x)
        word = word.replace(x, "")
        print(t)
        letters_guessed = letters_guessed[:t] + letters_guessed[t:t+1].replace('?', x) + letters_guessed[t+1:]


    elif type(x) is not str or len(x) > 1:
        print("Invalid guess, Your guess must be 1 letter long")
    else:
        print("Wrong!")
        guesses_left -= 1
        show_guesses_left()



def start_game():
    global letters_guessed
    global word
    global guesses_left
    letters_guessed = ''.join(hidden_word)
    while True:
        if guesses_left > 0 and len(word) != 0:
            request_guess()


        elif len(word) == 0:
            print(f"YOU WIN!!!, the word was {wordwin}")
            break

        else:
            print("You lose! Better luck next time!")
            break
start_game()

我继续得到这个结果,该结果仅对某些字母有效,并且放置错误。这是我的结果:

Welcome to Hangman!!
My word is 4 letters long
long
????
What is your guess? 
????l
Great you guessed a letter
0
What is your guess? 
l???n
Great you guessed a letter
1
What is your guess? 
ln??o
Great you guessed a letter
0
What is your guess? 
ln??g
Great you guessed a letter
0
YOU WIN!!!, the word was long

为什么我不能只将字符串切成一个字符并切成其余字符? 为什么它第一次起作用而不是第二次起作用? 如果有人可以向我解释发生了什么,将不胜感激

3 个答案:

答案 0 :(得分:0)

主要问题是,您基于在移动过程中修改的变量进行拼接。特别是变量word,在其中查找x的位置(即猜出的字母)。正确的位置,直到word的长度被修改为止,因为您将字母替换为空字符串。

一个简单的解决方法是简单地更改replace语句,并放置用户通常不会放置的空白或其他字符。在我的示例中,我将替换为:

word = word.replace(x, "")

使用

word = word.replace(x, " ")

这当然破坏了程序退出逻辑:您永远无法取胜。

还有另一个问题,那就是同一字母的多次出现没有正确地说明。实际上,当word中有相同字母的多个实例时,程序会循环运行直至耗尽。

这是由于find仅显示给定字母的第一个实例的位置,而您不考虑可能的重复项。

有几种解决方法,但是我认为主要问题已经确定。

有关其他实现,请选中https://eval.in/1051220

答案 1 :(得分:0)

解决方案

import random
guesses_left = 9
def show_guesses_left():
    print("You have", guesses_left, "guesses left")


wordlist = ['nerd', 'python', 'great', 'long', 'short', 'stupid', 'happy', 'programmer']
word = random.choice(wordlist)
wordwin = list(word)
hidden_word = list('?' * len(word))
letters_guessed = ''.join(hidden_word)

print("Welcome to Hangman!!")
print("My word is", len(word), "letters long")
print(letters_guessed)


def request_guess():
    global guesses_left
    global word
    global letters_guessed
    x = input("\nWhat is your guess?\n" + letters_guessed + "\n")

    if x in word:
        print("\nGreat you guessed a letter")
        for i, j in enumerate(word):
            if j == x:
                hidden_word[i] = j
        letters_guessed = ''.join(hidden_word)

        print(letters_guessed + "\n")
    elif type(x) is not str or len(x) > 1:
        print("Invalid guess, Your guess must be 1 letter long")
    else:
        print("\nWrong!")
        guesses_left -= 1
        show_guesses_left()



def start_game():
    global letters_guessed
    global word
    global guesses_left
    letters_guessed = ''.join(hidden_word)
    while True:
        if guesses_left > 0 and letters_guessed != word:
            request_guess()
        elif letters_guessed == word:
            print("YOU WIN!!!, the word was " + word)
            break

        else:
            print("\nYou lose! Better luck next time!")
            break
start_game()

注释

开始工作吧!

抱歉,时间不多会再次为您提供更多帮助,但请环顾四周。我使用了一些与您最初使用的方法不同的方法,似乎您的letters_guessed出现了一个问题,即没有显示已经猜到的字母后面的字母。这同样适用于双字母,这似乎也是您原始代码发出的。

再次抱歉,将再回来解释更多信息!

答案 2 :(得分:0)

主要问题是用于获取猜字母索引的代码:

    t = word.find(x)
    word = word.replace(x, "")

这会在每次正确的猜测之后缩短word,因此t将不是第一次正确的猜测之后的期望值。

但是,即使您解决了这个问题,您仍然无法正确处理猜出的字母多次出现的情况。

这是一个简短的示例,展示了如何解决这两个问题:

answer = 'long'
hidden = '?' * len(answer)
print("Welcome to hangman!")
while True:
    guess = input("Guess a letter: ")
    result = ''
    if guess in answer:
        for answer_letter, hidden_letter in zip(answer, hidden):
            if guess == answer_letter:
                result += guess
            else:
                result += hidden_letter
        hidden = result
    print(hidden)
    if hidden == answer:
        print("You guessed it!")
        break