Python Guess Game

Asked

Viewed 117 times

0

I was doing a job, and I ran into some problems. This code has a limitation: Whenever the player selects some number that has been selected before the code does not invalidate and is considered as an attempt. He wanted a help to refine the code and whenever the player gives a kick that he has already given previously, the program should refuse him and send a message informing the player about this situation and asking him to try another kick. Obviously, this double kick should not be counted as one of the 10 attempts the player is entitled to. I thought about creating an array of 10 elements but I got caught up in how to run

# apresente jogo ao usuário
print('Você tem 10 chances de acertar o número que eu estou pensando.')
print('Trata-se de um valor entre 1 e 100. Então, vamos lá!')
print()

# gere número-alvo entre 1 e 100
from random import randint
alvo = randint(1, 100)

# inicialize indicador de acerto
acertou = False

# repita 10 vezes:
contador = 0
while contador <= 10:

# obtenha palpite do usuário
while True:
try:
palpite = int(input('Entre o seu palpite: ')
if palpite < 1 or palpite > 100:
raise ValueError
break
except ValueError:
print('Palpite inválido. Tente outra vez!')
contador = contador + 1

# se palpite atingiu o alvo:
if palpite == alvo:

# atualize indicador de acerto
acertou = True

# encerre o jogo
break

# senão:
else:

# comunique erro ao usuário
print('Errou! Tente novamente.\n' \
'Você ainda tem ', 10-contador, ' tentativa(s).')
print(40*'-'+'\n')

# encerre o jogo
if acertou: # comunique sucesso ao usuário
print('Parabéns!\n' \
'Você acertou o número após ', contador, ' tentativa(s).')
else:

# comunique fracasso ao usuário
print('Infelizmente, você fracassou.\n', \
'O número pensado era: ', alvo, ' \n', \
'Quem sabe a próxima vez!')
print('Até breve') # emita saudação final

1 answer

0


It is difficult to say what is wrong with your code, or even what could be improved, because the indentation of your code in the question damaged the understanding. If you can edit the question by correcting the indentation, I can complete the answer with comments about your solution.

As an addendum, I put a way that I would solve the problem. As you want the attempts to be unique, that is, that the user does not enter with the same guess more than once, in fact, you will have to store them in some way. To this end, I will use the set which by default no longer allows duplicate values.

I’ll call the function print() to simplify the code, paying attention only to the implemented logic.

hunches = set()

As described, there will be two conditions of stops, exclusive to each other: when the user hits the drawn number; or when he reaches the limit of 10 guesses. So we have:

hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))
        ...
    except ValueError as e:
        print(e)

First, we validate whether the hunch is in the acceptable range:

hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')
    except ValueError as e:
        print(e)

Then, if the hunch has not been given previously:

hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')

        if hunch in hunches:
            raise ValueError('Você já deu este palpite antes')
    except ValueError as e:
        print(e)

Finally, we checked if the user hit the number; if yes, we defined that he was right, but if not, we added the guess to the set of guesses:

hit = False

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')

        if hunch in hunches:
            raise ValueError('Você já deu este palpite antes')

        if hunch == target:
            hit = True
        else:
            hunches.add(hunch)
    except ValueError as e:
        print(e)

At the end, we can check whether the user won or not:

print('Venceu' if hit else 'Perdeu')

The complete code would be:

from random import randint

target = randint(1, 100)

hit = False
hunches = set()

while not hit and len(hunches) < 10:
    try:
        hunch = int(input('Seu palpite:'))

        if not 1 <= hunch <= 100:
            raise ValueError('Palpite deve estar no intervalo [1, 100]')

        if hunch in hunches:
            raise ValueError('Você já deu este palpite antes')

        if hunch == target:
            hit = True
        else:
            hunches.add(hunch)
    except ValueError as e:
        print(e)

print('Venceu' if hit else 'Perdeu')

See working on Repl.it | Github GIST

  • Poooo thanks, took my doubt I did otherwise but now I have another problem. I want to give clues and tips to the user. I created two states one: hot and two: cold. Whenever the state 1 and 2 are equal, the program must send a message informing the player that the state of his kick is still the same, but that he gave a heated or a cold guess in relation to the previous guess. And I wanted to create 3 more states for the guess: Boiling (FV), Warm (MN) and Freezing (CG), following this order: FV -MQ -QT -MO -FR -MF -CG. The code does not error, massssss does not provide these hints.

  • @Renatosilva this seems to be problem for another question already

  • I’ll ask you another question and I’ll put the code so thank you very much for your help.

  • @Renatosilva if the answer was useful to you, seek to vote and accept it; see how to do in How and why to accept an answer?

Browser other questions tagged

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