简体   繁体   中英

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

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.

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:

______
_e__e_

An interesting function for strings is .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.

I'll leave it as an exercise to incorporate this in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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