Hangman in Python

Question:

I'm doing a hangman game in Python. At each loop the program asks for the letter or word:

#Jogo
perguntarNovamente = True
game_on = True
while game_on:
    palavra_secreta = palavra()
    senha_list = [l for l in palavra_secreta]
    chances = 6
    tentativas = []
    #Esconder palavra
    for i in range(101):
        print()
    print (senha_list) #APENAS PARA TESTE
    #Começo do jogo
    while perguntarNovamente:
        print("A palavra:","_ "*len(senha_list))
        erros = 0
        desenho(erros)
        an = input("Digite uma letra(ou a palavra): ")
        if an == palavra_secreta:
            print("Parabéns você acertou!!")
            break
        elif an not in(senha_list):
            if an in(tentativas):
                print("Você já tentou essa letra!")
                continue
            else:
                print("Não há essa letra na palavra!")
                tentativas.append(an)
                erros +=1
                continue
        else:
            print("Você acertou uma letra!")
            tentativas.append(an)
            continue
    break

Every time the player puts a wrong letter, the erros variable increases by 1, so I use it as a parameter to call the desenho function that draws the gallows and the puppet according to the number of errors:

def desenho(erros):
if erros == 0:
    print()
    print("|----- ")
    print("|    | ")
    print("|      ")
    print("|      ")
    print("|      ")
    print("|      ")
    print("_      ")
    print()
 #Não botei todos!! e está indentado!
 elif erros == 6:
    print()
    print("|----- ")
    print("|    | ")
    print("|    O ")
    print("|   /|\\ ")
    print("|    | ")
    print("|   / \\ ")
    print("_      ")
    print()

However, as the erros variable increases, the design does not change accordingly! How can I solve?

Code link: https://repl.it/Dbef/0

Answer:

Inside the while loop while perguntarNovamente: , you are initializing the variable erros = 0 , so every time the loop is executed, this variable is reset to zero.

A possible solution is to initialize erros before entering the loop:

#Começo do jogo
erros = 0 # AQUI => inicializa a variável erros fora do looping principal
while perguntarNovamente:
    print("A palavra:","_ "*len(senha_list))
    desenho(erros)
    ...
Scroll to Top