Problem comparing strings and string being broken into two python lines

Asked

Viewed 611 times

3

I was creating a game that scrambles words, and the user has 6 attempts to guess what the word is. I’ll put the code here:

import random

def main():
    while True:
        input('Presisone enter para sortear uma nova palavra.')
        palavra_oculta, dica = EscolhePalavra()
        palavra_embaralhada = EmbaralhaPalavra(palavra_oculta)
        palavra_embaralhada = palavra_embaralhada.lower()
        palavra_oculta = palavra_oculta.lower()
        tentativas = 6
        while tentativas != 0:
            print('\nA palavra embaralhada é: %s'%palavra_embaralhada)
            print('A dica é: %s'%dica)
            print('Você ainda tem %d tentativas.'%tentativas)
            palpite = input('Digite seu palpite: ')
            if palpite == palavra_oculta:
                print('Parabéns, você acertou!!!')
                break
            else:
                print('Ainda nao, tente novamente!')
                tentativas -= 1
        if tentativas == 0:
            print('Você perdeu! a palavra correta era %s.'%palavra_oculta)
        else:
            print('Parabéns, você acertou a palavra!!!')

def EscolhePalavra(): #Essa função está funcionando normalmente, a usei em outro jogo.
    lista_arquivos = {'Animais.txt' : 'Animal', 'Frutas.txt' : 'Fruta',
                      'Objetos.txt' : 'Objeto', 'Pessoas.txt' : 'Pesssoa',
                      'Profissões.txt' : 'Profissão'}
    arquivo_escolhido = random.choice(list(lista_arquivos.keys()))
    palavra = random.choice(open(arquivo_escolhido).readlines())
    dica = lista_arquivos[arquivo_escolhido]
    return(palavra, dica)

def EmbaralhaPalavra(palavra):
    palavra = list(palavra)
    random.shuffle(palavra)
    palavra = ''.join(palavra)
    return palavra

if __name__ == '__main__':
    main()

Let’s get down to business: First, with the word shuffled. For some reason I still don’t know which, when giving a print in palavra_embaralhada, most of the time it gets broken in two lines. I’ve tried to give a print on a separate line in the code, but the problem persists.

The second is that the comparison between the string written by the user stored in the variable palpite, and the palavra_oculta almost always come out wrong. I only got hit once. As much as I type the correct word, the program considers it to be two strings different. What I have to do?

1 answer

2


First, with the word shuffled. For some reason know which, when giving a print in word scrambled, most of the time it gets broken in two lines. I’ve tried to print it in one separate line in the code, but the problem persists.

  • The problem occurs in the function EmbaralhaPalavra, assuming that the variable palavra_oculta be of value Bar, when using the list, the value returned is a list containing ['B', 'a', 'r', '\n'], and when it shuffles with random.shuffle, happens the following (may vary): ['a', 'B', '\n', 'r'], that is, the reason for having line breaks, is due to new line which is created with the use of list. To fix this, you will need to remove the new line before shuffling. One way to do this is to use the method rstrip, there are also other ways.

    def EmbaralhaPalavra(palavra):
       palavra = palavra.rstrip()
       palavra = list(palavra)
       random.shuffle(palavra)
       palavra = ''.join(palavra)
       return palavra
    

The second is that the comparison between the string written by the user stored in the guess variable, and the hidden word almost always comes out wrong. I could only "hit" once. As much as I typed the correct word, the program considers it to be two strings different. What I have to do?

  • Same problem. Now in function EscolhePalavra, in the line where you open the file and read the lines:

    palavra = random.choice(open(arquivo_escolhido).readlines())
    

    The readlines() returns everything, including new lines, when comparing: if palpite == palavra_oculta.., is compared: Bar with Bar\n. To solve this, you can use the same solution that was used in the first problem, or use the method str.splitlines() instead of readlines(), this will eliminate the line breaks.

    def EscolhePalavra(): 
       lista_arquivos = {'Animais.txt' : 'Animal', 
                         'Frutas.txt' : 'Fruta',
                         'Objetos.txt' : 'Objeto', 
                         'Pessoas.txt' : 'Pesssoa',
                         'Profissões.txt' : 'Profissão'}
       arquivo_escolhido = random.choice(list(lista_arquivos.keys()))
       linhas = open(arquivo_escolhido).read().splitlines()
       palavra = random.choice(linhas)
       dica = lista_arquivos[arquivo_escolhido]
       return(palavra, dica)
    

    The comparison of strings in Python is case-sensitive, which can affect the outcome of the game as it is compared to the letters lowercase of the variable palavra_oculta with the value of the variable palpite, which may contain uppercase letters, also use the method lower() in palpite.

  • 1

    I didn’t know that splitlines(). Thanks for the answer!

Browser other questions tagged

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