K
If you want it loop continue, just do not interrupt it. In your case, you are using break, which interrupts loop, then just don't use it (or just use it when you really have to close). It was not clear whether it should "continue forever", but a suggestion would ask the user if he wants to continue playing. Something like this:while True:
# lógica do jogo
if senha == palavra_forca:
print(f"{nome} acertou!")
if input('Jogar novamente? S/N').lower() == 'n':
break
But that's not enough., because when restarting the game you have to re-seal the variables palavra_forca, digitadas, acertos and erros (since it's a new game starting). I suggest creating a function that returns this "zera" information, and then you can use it to seal the variables in the 2 cases that it is required (when the player hits or when the chances are exhausted). It would be like this:# ler o nome, etc...
def setup_inicial():
return (random.choice(palavra), [], [], 0)
palavra_forca, digitadas, acertos, erros = setup_inicial()
while True:
senha = ""
for letra in palavra_forca:
senha += letra if letra in acertos else "_ "
print(senha)
if senha == palavra_forca:
print(f"{nome} acertou!")
if input('Jogar novamente? S/N: ').lower() == 'n':
break
else: # "zera" as variáveis, iniciando um novo jogo as variáveis
palavra_forca, digitadas, acertos, erros = setup_inicial()
continue # aqui ele vai para a próxima iteração do loop, ignorando o restante abaixo
# ler a tentativa, imprimir o homem enforcado, etc...
if erros == 6:
print(f"{nome} foi enforcado!")
if input('Jogar novamente? S/N: ').lower() == 'n':
break
else: # "zera" as variáveis, iniciando um novo jogo as variáveis
palavra_forca, digitadas, acertos, erros = setup_inicial()
When using break, he leaves while True and continues running the code (if you have something after while). But if the idea is simply to leave the program, you can use https://docs.python.org/3/library/sys.html#sys.exit . In this case, I would use a slightly more "wait" function to check if it was typed "s" or "n" (because the way it is above, anything other than "n" makes the game continue).And since it is using https://docs.python.org/3/reference/lexical_analysis.html#f-strings (e.g. in print(f"{nome} acertou!")), no need to use % to print linha2 and linha3, use the same thing in their respective print's.Also used https://stackoverflow.com/a/2081708 so that </code> be interpreted correctly, since in strings this character is used for escape sequences, such as \n which indicates a line break (but in your case it does not seem to give problem because it coincided of not having an escape sequence, anyway, I put down too).And the variable that keeps all possible words could be called palavras (in plural). By calling her palavra (in singular), can pass the impression - wrong - that she only has one word. It may seem like a beast detail, but https://hackernoon.com/the-art-of-naming-variables-52f44de00aad .Anyway, it would be like this:import random
import sys
print('='*20)
print('JOGO DA FORCA')
print('='*20)
print('Bem vindo ao Jogo da Forca! Vamos começar!')
nome = input("Digite o seu nome: ")
palavras = ('uva','oi')
def setup_inicial():
return (random.choice(palavras), [], [], 0)
def continua_jogando():
while True:
opcao = input('Jogar novamente? s/n ').lower()
if opcao == 'n': # se digitou "n", sai do jogo (interrompe o programa)
sys.exit(0)
if opcao == 's': # se digitou "s", retorna o setup inicial com as variáveis "zeradas"
return setup_inicial()
# não digitou "s" nem "n", imprime a mensagem e pede que digite novamente
print('Digite "s" ou "n"')
palavra_forca, digitadas, acertos, erros = setup_inicial()
while True:
senha = ""
for letra in palavra_forca:
senha += letra if letra in acertos else "_ "
print(senha)
if senha == palavra_forca:
print(f"{nome} acertou!")
palavra_forca, digitadas, acertos, erros = continua_jogando()
continue # como vai reiniciar o jogo, use "continue" para ir direto para a próxima iteração do while, ignorando o que está abaixo
tentativa = input("\nDigite uma letra:").lower().strip()
if tentativa in digitadas:
print("Você já tentou esta letra!")
continue
else:
digitadas += tentativa
if tentativa in palavra_forca:
acertos += tentativa
else:
erros += 1
print("Você errou!\n")
print("X==:==\nX : ")
print("X O " if erros >= 1 else "X")
linha2 = ""
if erros == 2:
linha2 = " | "
elif erros == 3:
linha2 = r" \| "
elif erros >= 4:
linha2 = r" \|/ "
print(f"X{linha2}")
linha3 = ""
if erros == 5:
linha3 += " / "
elif erros >= 6:
linha3 += r" / \ "
print(f"X{linha3}")
print("X\n===========")
if erros == 6:
print(f"{nome} foi enforcado!")
palavra_forca, digitadas, acertos, erros = continua_jogando()
A https://pt.stackoverflow.com/a/458005/112052 (which has been deleted) is suggesting to use https://pt.stackoverflow.com/q/21551/112052 (create a function and call it inside itself).Although "functioning" is not the ideal solution. Every recursive call https://pt.stackoverflow.com/a/95826/112052 , and after a certain number of iterations, it may end up bursting the pile ( https://ideone.com/oJohIt an example).Already if you use one loop simple and interrupt it (be with break or with sys.exit), there is no such risk. The program can iterate as many times as you want the battery will not occur.