简体   繁体   English

如何用用户输入替换字符串的元素

[英]How do I replace elements of a string with user input

Below is code for a hangman game.下面是一个刽子手游戏的代码。 Everything thus far is working perfectly the only trouble I'm having is figuring out how to convert the underlined spaces with the correct letter when the user guesses correctly.到目前为止,一切都运行良好,我遇到的唯一麻烦是弄清楚如何在用户正确猜测时将带下划线的空格转换为正确的字母。 I have no code written for it and am looking for some help.我没有为它编写代码,正在寻求帮助。 All it does currently is return the blank underlines even if you do guess a number correctly它目前所做的只是返回空白下划线,即使您猜对了一个数字

import random

responses = {'title': 'Welcome to Hangman the Game!', 'rules':'Once you guess \
wrong 6 times you lose. Using the same letter twice does not count as a guess.', \
             'correct':'Well done, your guess is correct!', \
             'incorrect':'Sorry, your guess is incorrect...', \
             'win':'Well done, you win!', \
             'lose':'Out of guesses. You lose.'}

words = ['cat', 'dog', 'work', 'school', 'game', 'one', 'hangman', 'apple',
         'orange', 'list', 'words', 'bicycle', 'four', 'snowing', 'backpack',
         'computer', 'house', 'water', 'plant', 'hour']

game = random.choice(words)

print(game) # just in for ease of programming

guesses = 0

letter = []

length = len(game)

numletter = game.replace(game, '_ '*length) # display number of letters

while guesses < 6:
    print(numletter) # need to replace this with the code I will hopefully learn from this
    user = input('Guess a letter here: ')
    if user in game:
        if user not in letter:
            print(responses['correct'])

    if user not in game:
        if user not in letter:
            print(responses['incorrect'])
            guesses += 1


    if user not in letter:
        letter.append(user)

        print('You have guessed these letters', letter)

    else: 
        print('You have already guessed that letter, try again.')


    if user == game:
        print(responses['win'])
        break

else:
    print(responses['lose'])

Here is some output I get这是我得到的一些 output

water
_ _ _ _ _ 
Guess a letter here: a
Well done, your guess is correct!
You have guessed these letters ['a']
_ _ _ _ _ 
Guess a letter here: w
Well done, your guess is correct!
You have guessed these letters ['a', 'w']
_ _ _ _ _ 
Guess a letter here: w
You have already guessed that letter, try again.

As you can see the blanks remain unchanged]如您所见,空白保持不变]

Maintain a list of booleans, visibility such that visibility[5] is true if and only if you want character #5 in the string to be visible.维护一个布尔值列表, visibility性当且仅当您希望字符串中的字符#5 可见时visibility[5]为真。

import io
class HiddenString:

    def __init__(self, word):
        self._word = list(str(word))
        self._visibility = [False]*len(self._word)

    def make_all_instances_visible(self, char):
        char = str(char)
        assert(len(char) == 1)
        for idx in range(len(self._word)):
            if self._word[idx] == char:
                self._visibility[idx] = True
        return

    def __str__(self):
        with io.StringIO() as string_stream:
            for idx in range(len(self._word)):
                char = "_"
                if self._visibility[idx]:
                    char = self._word[idx]
                print(char, end="", file=string_stream)
            stryng = string_stream.getvalue()
        return stryng

###################################################################

secret = HiddenString("secret")
print(secret)
secret.make_all_instances_visible("e")
print(secret)

Below is the console output:下面是控制台output:

______
_e__e_

An interesting function for strings is .translate() .一个有趣的字符串 function 是.translate() It takes a dictionary of ordinal values for characters and translate them to the values of the dictionary.它需要一个字符序数值字典,并将它们转换为字典的值。 so if you put all the ordinals for the solution word in the translation table, translating them to underscores, and translate the word, you'll get underscores for everything:因此,如果您将解决方案单词的所有序数放在翻译表中,将它们翻译为下划线,然后翻译该单词,您将得到所有内容的下划线:

>>> word = 'apple'
>>> xlat = {ord(c):'_' for c in word}
>>> xlat
{97: '_', 112: '_', 108: '_', 101: '_'}
>>> word.translate(xlat)
'_____'

Now when you have a guess, test if that ordinal key is in the translation table, and if so, remove it.现在,当您有猜测时,测试该序号键是否在翻译表中,如果是,则将其删除。 When you translate again, the replacement won't occur for the removed letter:当您再次翻译时,删除的字母不会发生替换:

>>> guess = 'p'
>>> ord(guess) in xlat
True
>>> del xlat[ord(guess)]
>>> word.translate(xlat)
'_pp__'

When word.translate(xlat) == word the game is won.word.translate(xlat) == word游戏获胜。

I'll leave it as an exercise to incorporate this in your code.我将把它作为一个练习来合并到你的代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM