Replace specific character on list in Python with on loop

I'm a newbie in coding and I tried to do my own hangman game when I encounter a big bug that I cannot solve. I gotta be honest, I'm not too familiar when it comes to modify list so that might be why I cannot solve this. The following piece of code is a function that takes some parameters and tries to return the modified blankSpaces as a not-so-blank-spaces, so for example if the user tries to guess with ther word "o", but the word is not on the list of the original word, lets say for example "love", the blankSpaces for love would be something like "_ _ _ _", so I'm trying to do that if the letter "o" is inside the original word I would take the position of the original word and replace it on the blankSpaces to return something like "o_" because its on the original string:

def revealWord(blankSpaces, letterToReveal, wordPosition, actualString):
countChar = len(actualString)
dividedString = list(actualString)
chara = letterToReveal
joinWord = []

y = 0
while y < countChar:
    y += 1
    if letterToReveal == dividedString[y - 1]:
        print("matched")
        joinWord = dividedString[y - 1]

joinWord = " ".join(blankSpaces)
return joinWord

so, for me when I try to guess the word I get something like this your word kinda looks like this: this is the output:

_ _ _ _
try to guess typing a single letter, you have 6 attempts remaining
What is your letter?
 -o
You guessed right! Your letter -o- is #1 time/s in the original word
matched
your word now looks like this: --- _ _ _ _ ---
try to guess typing a single letter, you have 6 attempts remaining
What is your letter?
 -

See? It doesn't modify anything... Attaching the entire code for better context

import random

wordsdb = ["water", "airplane", "love"]

def keep_playing(currentLives, wordSlctd, blankSpaces):
    print("try to guess typing a single letter, you have {} attempts remaining" .format(currentLives))
    charToGuess = input("What is your letter? \n -")
    check_if_char(blankSpaces, wordSlctd, charToGuess, currentLives)

def hangItUp(hp, wordSlctd, blankSpaces):
    hp -= 1
    print("Your character is not on the string. Hanging him up!")
    print("{} attempts remaining " .format(hp))
    if hp <= 0:
        userResponse = input("Game Over! Waiting for your response...")
        if userResponse == "try again":
            print("restarting the game.")
        else:
            print("Bye bye...")
    else:
        keep_playing(hp, wordSlctd, blankSpaces)
    return hp

def revealWord(blankSpaces, letterToReveal, wordPosition, actualString):
    countChar = len(actualString)
    dividedString = list(actualString)
    chara = letterToReveal
    joinWord = []

    y = 0
    while y < countChar:
        y += 1
        if letterToReveal == dividedString[y - 1]:
            print("matched")
            joinWord = dividedString[y - 1]

    joinWord = " ".join(blankSpaces)
    return joinWord

def check_if_char(blankSpaces, ogWord, selectedChar, currentLives):
    countChar = len(ogWord)
    wordSplitted = list(ogWord)
    wordCount = wordSplitted.count(selectedChar)
    matchedIndexes = []
    revealedWord = ogWord

    if selectedChar in wordSplitted:
        x = 0
        while x < countChar:
            x += 1
            if selectedChar == wordSplitted[x - 1]:
                matchedIndexes.append(x)

        print("You guessed right! Your letter -{}- is #{} time/s in the original word" .format(selectedChar, wordCount))
        revealedWord = revealWord(blankSpaces, selectedChar, matchedIndexes, ogWord)
        print("your word now looks like this: --- {} ---" .format(revealedWord))
        keep_playing(currentLives, revealedWord, blankSpaces)
    else:
        print("your actual word: --- {} ---" .format(revealedWord))
        print("your current word: --- {} ---" .format(blankSpaces))
        currentLives = hangItUp(currentLives, revealedWord, blankSpaces)
        keep_playing(currentLives, revealedWord)



def hangman_game():
    lives = 6
    theSelectedWord = random.choice(wordsdb)
    countTheBlankSpaces = len(theSelectedWord)
    theBlankSpaces = []


    for i in range(countTheBlankSpaces):
        theBlankSpaces.append("_")

    print("your word kinda looks like this: {} " .format(" ".join(theBlankSpaces)))
    keep_playing(lives, theSelectedWord, theBlankSpaces)

hangman_game()

Upvotes: 2

Views: 463

Answers (2)

Alderven
Alderven

Reputation: 8260

You can simplify your logic by keeping list of guessed letters. Thus, you don't need blankSpaces, letterToReveal, wordPosition and actualString variables. You can also use guessed letters list for checking victory condition.

import random

WORDS = ["water", "airplane", "love"]


def revealed_word(word, guessed_letters):
    result = []
    for letter in word:
        if letter in guessed_letters:
            result.append(letter)
        else:
            result.append('-')
    return result


def hangman_game(lives, word):
    guessed_letters = []

    while lives and len(guessed_letters) < len(set(word)):
        print(f"your word kinda looks like this: {revealed_word(word, guessed_letters)}")
        print(f"try to guess typing a single letter, you have {lives} attempts remaining")
        guess = input("What is your letter? ")
        if guess in guessed_letters:
            print("you already guessed this letter, try another one")
        elif len(guess) == 1:
            if guess in word:
                print(f"You guessed right! Your letter -{guess}- is #{word.count(guess)} time/s in the original word")
                guessed_letters.append(guess)
            else:
                lives -= 1
                print("Your character is not on the string. Hanging him up!")
                print("{} attempts remaining ".format(lives))
        else:
            print("please enter one letter only")

    action = input("Game Over! Waiting for your response...")
    if action == "try again":
        print("restarting the game.")
        hangman_game(lives=6, word=random.choice(WORDS))
    else:
        print("Bye bye...")


hangman_game(lives=6, word=random.choice(WORDS))

Sample output:

your word kinda looks like this: ['-', '-', '-', '-', '-', '-', '-', '-']
try to guess typing a single letter, you have 6 attempts remaining
What is your letter? a
You guessed right! Your letter -a- is #2 time/s in the original word
your word kinda looks like this: ['a', '-', '-', '-', '-', 'a', '-', '-']

Upvotes: 1

im_baby
im_baby

Reputation: 988

I believe the issue is that you are simply returning a series of blank spaces every time because of this:

joinWord = " ".join(blankSpaces)
return joinWord

You are trying to format it later in the 'check_if_char' function:

revealedWord = revealWord(blankSpaces, selectedChar, matchedIndexes, ogWord)
print("your word now looks like this: --- {} ---".format(revealedWord))

This makes it so the output will always have the blank spaces in that print statement.

Try updating your loop like this.

    while y < countChar:
        y += 1
        if letterToReveal == dividedString[y - 1]:
            print("matched")
            blankSpaces[y - 1] = letterToReveal
    joinWord = " ".join(blankSpaces)
    return joinWord

Now you are modifying the index of the letter in the blankSpaces list so it actually contains the letter you want to reveal. Now when you .join() the list looks how you want!

Upvotes: 0

Related Questions