Python: Problem with random numbers within while

Asked

Viewed 70 times

0

I would like to know how to solve a small problem I am facing in this and other codes.

When testing the example you will realize that it will use the same atk always, that is if he chooses the atk 1, he’s gonna take this one atk by the end of the code.

I would like every repetition he chose a different variable, instead of choosing one randomly and staying in every repetition, I wanted every repetition he chose another variable.

from time import sleep
import random
#------------------jogador------------------#
Hp_Jogador   = 120
Atk_Jogador  = 20
Atk_Jogador1 = 30
Atk_Jogador2 = 40
#------------------inimigo------------------#
Hp_Inimigo   = 120
Atk_Inimigo  = 20
Atk_Inimigo1 = 30
Atk_Inimigo2 = 40
list = [Atk_Inimigo, Atk_Inimigo1, Atk_Inimigo2 ]
atki = random.choice(list)
r = 0
print('Você encontrou um inimigo!')
sleep(1)
print(f'Inimigo HP:120')
print('Jogador HP: 120')
while Hp_Inimigo > 0 or Hp_Jogador < 0:
    r += 1
    sleep(1)
    print(f'-=-round {r}-=- ')
    print()
    sleep(2)
    print('[1] Bola de fogo: 20')
    print('[2] Estaca de gelo: 30')
    print('[3] Elétro Shock: 40')
    print()
    #-------------------jogador------------------#
    a = int(input('Escolha seu ataque:'))

    if a == 1:
        Hp_Inimigo = Hp_Inimigo - Atk_Jogador
    if a == 2:
        Hp_Inimigo = Hp_Inimigo - Atk_Jogador1
    if a == 3:
        Hp_Inimigo = Hp_Inimigo - Atk_Jogador2
    print()
    print(f'HP Inimigo: {Hp_Inimigo}')

#-------------------inimigo------------------#
    Hp_Jogador = Hp_Jogador - atki
    print(f'Hp_Jogador: {Hp_Jogador}')
    if Hp_Inimigo <= 0:
        print("Você venceu")
        break
    elif Hp_Jogador <= 0:
        print('Você perdeu')
        break
  • Play this: atki = random.choice(list) into the while.

  • 1

    Take that line atki = random.choice(list) and insert at the beginning of the loop while Hp_Inimigo > 0 or Hp_Jogador < 0: see if this is what you’re looking for?

1 answer

-1

I couldn’t quite understand your code, but apparently the problem is that you’re using a variable to generate a random number, when in fact, you should be generating a random number for each ATK_Jogador. Storing an Random function in a variable causes when the program reads its code, make the variable have the static random value and the same will not change every time you call for the variable. To resolve this in your code replace:

Atk_Jogador(n)

for

random.choice(sua_lista)

Browser other questions tagged

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