-1

So I've been trying to make a basic text game in python, and I'm using this code to constantly generate random numbers for use in certain functions to decide if the player is damaged, the player is attacked, etc.:

    rng = random.randint(0,100)
    while True:
            rng = random.randint(0,100)

My first line of code that is actually displayed to the user, which asks if the player would like to play, won't run when I put the loop to generate random numbers at the start of my program. PyCharm says that the code is unreachable. How can I solve that? Here is that line, for reference:

    game = raw_input("Would you like to play? Y/N\n")

Nothing is displayed on the screen when I run the program, unless I take out the loop. Sorry if the answer is obvious, I've only been working on python for a short amount of time.

Ppick
  • 13
  • 5
  • 1
    From what I can see, your loop is infinite. True is always True, and therefore the program will enter the loop and never break out. – Carter Jul 28 '17 at 22:18
  • 'Nothing is displayed on the screen when I run the program, unless I take out the loop.' Then take out the loop. – Tamas Hegedus Jul 28 '17 at 22:21
  • "I'm using this code to constantly generate random numbers" - are you under the impression that Python will run this loop in the background, constantly replacing the value of `rng` while other code goes on to do other things? That's not how things work, and it's a terrible way to manage random numbers even if you go through the work to actually have this loop run concurrently with other code. – user2357112 Jul 28 '17 at 22:22
  • @Tamas Hegedus if I take out the loop, then it will only generate a single number, which I don't want. I want random numbers to consistently be generated, so that the user doesn't get either the bad outcome or the good outcome every single time. I want the user to sometimes get a good outcome and sometimes a bad outcome in every situation. – Ppick Jul 28 '17 at 22:25
  • 1
    Generate random numbers when you actually need them. – user2357112 Jul 28 '17 at 22:44

1 Answers1

0

As has been alluded, your while loop will run forever and has no mechanism to break out of the while loop.

while True:
    # do something

This never stops, because the while loop is effectively doing this test:

while True == True:
    # do something

As noted, you are better off doing something like this:

game = raw_input("Would you like to play? Y/N\n")

# do stuff
# AND NOW, simulating some of the items you mentioned...

if random.randint(0, 100) > 70:
    # enemy attacks

if random.randint(0, 100) > 50:
    # player experiences damage 
E. Ducateme
  • 4,028
  • 2
  • 20
  • 30