Python Combat Game

6

I'm a beginner in programming and I'm trying to make a simple little game to apply my knowledge about conditionals, repetition and the Random module, but I'm having some semantic problems.

My goal is to attack the monster with a random number between 1 and 6 until HP drops it to a value equal to or less than zero and when doing so indicates that the monster has expired, but I'm basically having two problems:

  • I want the player to have the option to attack or not and to display a message in case he decides not to attack.
  • I want to display a win message that appears only when the player wins the monster.

Here is the code:

from random import randint
print('Um monstro apareceu !')
hp=10
a=randint(1,6)
while hp-a>0:
  hp=hp-a
  d=input('Deseja atacar o monstro (S/N) ? ')
  if d=='S':
    print(hp-a,)
  if hp<=0:
    print('Você venceu o monstro !')
if d=='N':
  print('Você fugiu !')

The problem is that the victory message is not being displayed and the message that the player does not want to attack is always appearing. Could someone help me?

    
asked by anonymous 08.02.2018 / 19:10

1 answer

6

Basically you have 3 main problems:

  •   

    a = randint (1,6)

  • This line only happens once before the while loop, so the value of a will not change, it seems to me that it should be in the loop and be the first thing to do when the user answers 'S' .

  • You are decrementing too many times a to hp , which can lead to false data to be shown, to logic being bugged:
  •   

    While hp-a > 0:
      ...
      hp = hp-a
      ...
      print (hp-a)

  • Victory message is not being displayed "has to do with point 2, when checking while hp-a>0 it exits the loop without hp=hp-a , and it does not even enter if hp<=0: when actually hp <= 0 .
  • That said, you can simplify it to:

    from random import randint
    
    hp = 10
    while hp > 0:
        d = input('Deseja atacar o monstro (S/N) ? ')
        if(d == 'S'):
            a = randint(1,6)
            hp = hp - a # novo valor do hp
            print('ataque de {} pontos, {} de hp restante do monstro'.format(a, hp)) # imprimir hp restante
        else:
            print('Você fugiu !')
            break
    else: # se saiu do ciclo while sem haver break e porque o monstro ficou com hp <= 0
        print('Você venceu o monstro !')
    

    DEMONSTRATION

        
    08.02.2018 / 19:29