Ad

How To Add Random Action To Python?

- 1 answer

I've been coding an adventure game in Python myself and through YouTube and stuff I found online, but I want to add a part where You gotta get on this boat but a ticket costs $10 (Which you have an option to get earlier).

But say you didn't get the 10 earlier, you have another option to run past the guy who's asking you to pay for it (Which I guess you Could also do even if you have the 10 and just save money). But if you have $10, you just go through, and if you don't, you just restart and it runs sys.exit()

As of writing, the code looks like this:

print("A man offers you a trip to the eastern side of the village via boat")

print(
    "as a bridge has not been constructed yet, but it will cost $10, do you give him it ($10 Required) or try run past him(Free)")

check_inv = input()

if "$10" not in inv:
    print("He caught you making a run for it! restart game")
    sys.exit()

else:
    
  print("Let's see if you have enough...")
    
  print(inv)
    
  print("You have enough and cross the river")
    
  removeFrominventory("$10")

I know how to write a random number generator as it was another beginner project I was advised to work on, but I want to to be that if you type 'Run' you will have a 50/50 chance to be able to outrun him.

Ad

Answer

Assuming you want it to be like the RNG in pokemon or want to create a coin flip event, you could either create a list of list = [0,1] and use random.choice(list) or you could use randrange() to get a number b/w 0 and 100. Let's say the chances to outrun are x%. If the value obtained from randrange is less than x, you outrun else you don't. You can create a function like:

def RNG(probability):
    Generate Random num b/w 0 and 100
    if num<probability:
        return True
    else:
        return False

I would prefer the RNG function. Though it is time and memory consuming, it can be reused in the code again and again.

Ad
source: stackoverflow.com
Ad