Match Checking Python Hangman game

Asked

Viewed 470 times

0

I’m finishing the Python hangman game. But I’m having trouble with the final check when the player hits the word, I’m not able to create a check to validate if the player hit the word, could help me?

from random import randint

def tentativa1():
    print('''
|─|─────────────────|
| |               (o.o)
| |
| |
| |
| |
| |
| |
|_|=====================
você tem 6 tentativas
========================
''')
def tentativa2():
    print('''
|─|─────────────────|
| |               (o.o)
| |                ||
| |                ||
| |                ||
| |
| |
| |
|_|=====================
você tem 5 tentativas
========================
''')
def tentativa3():
    print('''
|─|─────────────────|
| |               (o.o)
| |                ||_
| |                || \\
| |                ||  \\
| |
| |
| |
|_|=====================
você tem 4 tentativas
========================
''')
def tentativa4():
    print('''
|─|─────────────────|
| |               (o.o)
| |               _||_
| |              / || \\
| |             /  ||  \\
| |
| |
| |
|_|=====================
você tem 3 tentativas
========================
''')
def tentativa5():
    print('''
|─|─────────────────|
| |               (o.o)
| |               _||_
| |              / || \\
| |             /  ||  \\
| |                /
| |              _/
| |
|_|=====================
você tem 2 tentativas
========================
''')
def tentativa6():
    print('''
|─|─────────────────|
| |               (o.o)
| |               _||_
| |              / || \\
| |             /  ||  \\
| |                /\\
| |              _/  \\_
| |
|_|================================
Última Chance !!! Tome cuidado !!!
===================================
''')
def campeao():
    print(''' =-=-=-=-=- PARABÉNS VOCÊ GANHOU !!!! =-=-=-=-=-''')
def final():
    print(''' ========== VOCÊ PERDEU !!! ==========''')

lista_palavras = ["casa", "shopping", "palio", "palmeiras", "lakers", "lucas", "acdc", "dinossauro"]
lista_dicas = ["DICA: Local de descanso...", "DICA: Ir as compras...", "DICA: Carro popular", "DICA: Time sem mundial...", "DICA: Time da NBA...", "DICA: Companheiro de sala conhecido como Nethoes...", "DICA: Banda de Rock...", "DICA: Animal Pré Histórico..."]

print('''====================================
       JOGO DA FORCA - IFPR
====================================''')
print("\n")

print('''====================================
    Pronto para Começar...?
====================================''')
print("\n")

aceita = 1
n_aceita = 0

while True:
    inicio = int(input("Digite (1) para Inicar ou (0) para Sair: "))

    if inicio == 1:

        pos = randint (0, len(lista_palavras)-1)
        palavra = lista_palavras[pos]
        riscos = [" _ "] * len(palavra)

        letras_digitadas = []
        letras_descobertas = []

        print("\n")
        print("Começando o jogo....FORCA - IFPR")

        print("\n")
        print(lista_dicas[pos])
        print("\n")
        print(riscos)
        print("\n")

        erros = 0
        acertos = 0

        while erros < 7 :
            letra = input("Digite uma letra: ").lower()

                if letra in palavra:
                pos = palavra.find(letra)
                for i in range(pos, len(palavra)):
                    if letra == palavra[i]:
                        riscos[i] = letra

            else:
                erros = erros + 1

            if erros == 1:
                tentativa1()
            elif erros == 2:
                tentativa2()
            elif erros == 3:
                tentativa3()
            elif erros == 4:
                tentativa4()
            elif erros == 5:
                tentativa5()
            elif erros == 6:
                tentativa6()
            if erros == 7:
                final()
                break

            print(riscos)

        # Condição para verifcar se a letra já foi digitada.

            if letra in letras_digitadas:
                print("Você já tentou essa Letra. Digite Novamente !!!")

            else:
                letras_digitadas.append(letra)

    else:
        print("Saindo do jogo....")
        print("\n")
        print("Obrigado!")
        break

2 answers

0

If the word the player has to hit is the variable palavra, and you keep the letters that he hit the list riscos then you can compare the palavra with the conversion into string of lista using the join.

Logo on the code just put:

while erros < 7 :
    # (...) o resto do codigo  

    # como ultima instrução do while
    if palavra == ''.join(riscos):
        campeao()
        break

There are many things that can improve and do differently, but only indicating the simplest:

  • To get better when it shows the riscos may use the same technique as in the comparison, making print(' '.join(riscos)). Notice that I used ' '.join with space for the risks to be spaced.

  • You must not initialize the riscos with spaces next to the _ as he did:

    riscos = [" _ "] * len(palavra)
    #          ^-^
    

    This is visual formatting that you should do only when it will show to the player. Do before:

    riscos = ["_"] * len(palavra)
    
  • Do not create a function for each error value:

    if erros == 1:
        tentativa1()
    elif erros == 2:
        tentativa2()
    elif erros == 3:
        tentativa3()
    elif erros == 4:
        tentativa4()
    elif erros == 5:
        tentativa5()
    elif erros == 6:
        tentativa6()
    

    Instead receive the amount of errors in the function that shows the dummy, and draw the right dummy based on that amount:

    def tentativa(erros):
        if erros == 1:
            #desenho do 1
    

    This will make the block ifs previously showing in:

    tentativa(erros)
    

    There are even parts of the drawing that are the same in all cases, which you may want to repurpose and do regardless of the number of errors.

  • Friend, I tried to put the def of the attempts as you showed but I could not, could help me?

  • @It’s hard to say anything without seeing how you applied it. In any case, the question should not be changed because it distorts the answers. If you want you can leave a link of a Pastebin for example, of how you applied, or open a new question.

  • Okay, I’m sending you the link to Pastebin for a look: https://pastebin.com/SdynXS5d

  • @That wasn’t like I said in the answer. The way I said you only have one function tentativa and not 6 functions, and within that single function writes with print what matters based on ifs on a variable indicating errors. main is just tentativa(erros) before the verification of the champion, nothing more.

0


One way is to test if there are still risks in riscos:

while erros < 7 :
    if ' _ ' not in riscos:
        print('Voce ganhou')

Testing:

DICA: Animal Pré Histórico...

[' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ']
Digite uma letra: d
['d', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ']
Digite uma letra: i
['d', 'i', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ']
Digite uma letra: n
['d', 'i', 'n', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ']
Digite uma letra: o
['d', 'i', 'n', 'o', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', 'o']
Digite uma letra: s
['d', 'i', 'n', 'o', 's', 's', ' _ ', ' _ ', ' _ ', 'o']
Digite uma letra: a
['d', 'i', 'n', 'o', 's', 's', 'a', ' _ ', ' _ ', 'o']
Digite uma letra: u
['d', 'i', 'n', 'o', 's', 's', 'a', 'u', ' _ ', 'o']
Digite uma letra: r
['d', 'i', 'n', 'o', 's', 's', 'a', 'u', 'r', 'o']
Voce ganhou
  • In the event of the scratch check, will he stay out of the loop? Because when I put that risk if, so I type the first word it already appears as Won by not completing the other positions?

  • @Mayconwillianalvesdasilva would have to be inside the loop, inside while erros < 7 :, after you have already set the variable riscos

  • Yes, I put more also does not appear the check as Won when hit the word.

  • @Mayconwillianalvesdasilva put the exact site of the while in question, and also my test - here ran beauty!

  • @Mayconwillianalvesdasilva as you can see in the answer I put the if right underneath while erros < 7:

  • Thank you! Now it worked. Just missed it return to the options menu when the player won.

  • @Mayconwillianalvesdasilva, now that it’s worked, would you please mark my answer as accepted, to close the question? Just click on the green Checkmark next to the answer.

  • Yes, I managed to finish. More as I do this I didn’t find this Checkmark

  • @Mayconwillianalvesdasilva on the side of my answer, below the voting buttons, passes the mouse will appear a green V, click on it. See image here

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.