Python Forum

Full Version: Life counter not working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I'm trying to make hangman but the lives lost never go past 1, here's my code:


import random
livesLost = 0
words=["forrest","donkey","pineapple","chicken","cat","elephant","zebra","headphones","book","trees","minecraft","spiderman","window","house","batman","car","computer","jazz","japan","fortnite","blue","purple","alphabet","money","highlighter","speaker","hangman","globe","earth","river","moustache","test","table","pancakes","chocolate","superman","keyboard"]
def wordChoice(words):
    word=random.choice(words)
    return(word)

def maskGen(myWord):
    lengthOfWord=len(myWord)
    x = 0
    mask = ""
    while x < lengthOfWord:
        mask = mask + "_"
        x = x +1
    return(mask)

def guess(myWord,wordMask,lengthOfWord,livesLost):
    guess=input("Guess a letter: ")
    correct = False
    for i in range(lengthOfWord):
        if myWord[i] == guess:
            wordMask = wordMask[:i] + guess + wordMask[i+1:]
            correct = True
    if not correct:
        livesLost = livesLost + 1
        print("Life Lost")
        print(livesLost)
    return livesLost
    print(wordMask)
    return wordMask

def wordComplete(wordMask,myWord,lengthOfWord):
    
    for i in range(lengthOfWord):
        if wordMask[i]=="_":
            return False

    return True

print("You have 9 lives total, just like a cat, until the man is hung")

myWord=wordChoice(words)
lengthOfWord=len(myWord)

wordMask= maskGen(myWord)
print(wordMask)

wordFinished = False
        
print(myWord)
while wordFinished == False:
    wordFinished = wordComplete(wordMask,myWord,lengthOfWord)
    wordMask = guess(myWord,wordMask,lengthOfWord,livesLost)
    livesLost = guess(myWord,wordMask,lengthOfWord,livesLost)
print("You have guessed the word, well done!")
print("You lost",livesLost,"lives")
The code gives
Error:
TypeError: 'int' object is not subscriptable
The function guess is called twice to get the return of wordMask and livesLost.
It currently only returns livesLost (the first return it gets to)
To make it work you could change the code to only call guess once and return both wordMask and livesLost

def guess(myWord,wordMask,lengthOfWord,livesLost):
    ...
    ...
    if not correct:
        livesLost = livesLost + 1
        print("Life Lost")
        print(livesLost)
    return livesLost, wordMask
    # print(wordMask)
    # return wordMask

...
...
while wordFinished == False:
    wordFinished = wordComplete(wordMask,myWord,lengthOfWord)
    # wordMask = guess(myWord,wordMask,lengthOfWord,livesLost)
    livesLost, wordMask = guess(myWord,wordMask,lengthOfWord,livesLost)