Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add random action to python?

First of all, I should say I’m a beginner in programming and I’ve only been doing this for about a month now, maybe 3 weeks (I don’t really Keep track).
Anyways as a project I’ve been coding a VERY basic adventure game in Python myself and through YouTube and stuff I found online, but I want to add a part where basically 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")

-END OF CODE-
(btw the code formatting does NOT look like this, but I don’t know how StackOverflow’s line spacing system works)

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.

Thanks for any help in advance!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading