Python Guess Game

0

I was doing a job and I ran into some problems. This code has a limitation: Whenever the player selects any number that has already been selected before, the code does not invalidate and is considered as an attempt. I would like a help to refine the code and whenever the player gives a kick that he has already given, the program should refuse it and send a message informing the player about this situation and asking him to try another kick. Obviously, that duplicate kick should not be counted with one of 10 attempts the player is entitled to. I thought about creating an array of 10 elements but I wrapped myself 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
    
asked by anonymous 15.05.2018 / 19:44

1 answer

0

Difficult to say what is wrong with your code, or even what could be improved, as the indentation of your code in the question hindered 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. Since you want the attempts to be unique, that is, that the user does not make the same guess more than once, in fact, you will have to store them in some way. To do this, I'll use set , which by default no longer allows duplicate values.

  

I will remove the calls to the print() function to simplify the code, paying attention only to the implemented logic.

hunches = set()

As described, there will be two stop conditions, unique to each other: when the user hits the number drawn; or when you reach 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 if the guess 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 guess 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 check if the user has hit the number; if yes, we defined that it was correct, but if not, we add the guess to the set of hunches:

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 or not the user won:

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

The complete code would look like:

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 at Repl.it | GitHub GIST

    
16.05.2018 / 00:39