How to add random action to Python? - python

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.

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.

Related

Can I get code to stop if a variable reaches zero?

I have been wanting to get into coding videogames, I am 15 and decided to try and start off making a text based game in python since I am not sure how to go about starting to make videogames (any advice on this would also be helpful :])
I was wondering if there was a way to get a program to stop if a variable reaches zero without having "if health == 0" everywhere in my code, should I use a while loop or is there another method I can use?
Try using
while(variable!=0):
your statement
Using this you can run your code unless the variable reaches 0. Hope it helps. Happy coding :) champ!
As in your case you know the condition (i == 0) to stop iteration, while loop will be the best option to choose among other types of loops. Do consider using functions to make sure code reusability.
Refer to the below code snippet to avoid using if health == 0
health = 5
while health:
print(health)
health -= 1
Output: 5 to 1

How would I sent user to new "block" instead of continue same path?

response = ""
while response not in directions_window:
print("While crouched below the window you begin weighing you options")
print("You decide your only options are to listen in, knock on window, or wait")
response = input("Which are you doing?\nlisten/knock/wait")
if response == "listen":
print("You raise your head slightly to hear better\n")
print("You can ony make out a few words before the figure inside sees you\n")
print("Latin words can be heard screaming as it charges towards the window\n")
print("You try to run away, but slip and fall on your stomach.\n")
print("The figure catches up to you only to knock you unconsious.\n")
print("You wake up with scratches and marks around your wrist\n")
print("Taking in your surroundings, you notice you're at the entrance to the forest.\n")
print("You cut your losses, and leave the forest. Forever wondering who, or what, that was.\n")
quit()
I'm in the process of making a text-based adventure game. I want to send the user to a new "part" of the game if this option is selected instead of quit(). How would I skip to a new block? Also, I know I can write it without print every line, but I wrote this over time as ideas came to me. Will fix later
What you might be looking for is to use functions to branch your adventure's "path" into different "sections" which each direct the user to a different area (and can even loop the user back to an area they were before if desired), like this:
def adventure_listen():
print("you picked listen")
# ... more text
response = input("Which do you pick?\nA/B")
if response == "A":
do_something()
elif response == "B":
do_something_else()
def adventure_knock():
# code similar to above
def adventure_wait():
# code similar to above
print("message1")
response = input("Which are you doing?\nlisten/knock/wait")
if response == "listen":
adventure_listen()
elif response == "knock":
adventure_knock()
elif response == "wait":
adventure_wait()
"Jumping blocks" as you call it, is something that is used in assembler code. In high level languages (such as python), flow control structures are used (if else, for loops, while, etc).
For your specific case, if you decide to use flow control structures, and your story is long you will sooner than later get lost in your own code. Functions, as proposed by Cristopher Rybicki, would be a better way to go. For this you should either (a) first know your story in advance and/or (b) find a common structure or pattern in your story that allows you to "open" and "close" chapters.
(a) because it will help you structure better your code
(b) because if you cannot draw at first your story it will help you keep a structure and follow some patterns.
Execution of code is sequential, so you (cannot) should not "jump" from one function to another avoiding (or hoping to) the code after some "branch" line not to execute.
The more advanced approach (and the one I would recommend), is to go with classes and learn your way through inheritance. So your program could have Actions, Moves or whatever you choose it to have. Because you might now want to adventure_knock, and later it might be adventure_throw_the_door_down. They both (i) come from another step in the story, (ii) will have a feedback given to the user, and (iii) will have to go back to a point in the story.
in your main execution you can have a loop that initiates your stories, chapters?, and so on.
a pseudocode example would be:
Action:
abstract function start_action:
...
abstract function end_action:
...
abstract function give_feedback:
...
function ask_for_input:
input('What are you waiting for?')
Knock extends Action:
function start_action:
#specific implementation of knock...
...

Generating Random Numbers for a Combat Simulator

I am attempting to create a very basic Combat Simulator. Here is my code:
import random
#from random import * I had, at one time, created a D20 generator that used the * function. I have since removed it in favor of using randint()
sword = 0
D20 = 0
class Hero:
def swing_and_hit(sword, D20):
sword = D20
print(D20)
if sword >= 10:
print("You have defeated the Villian!")
elif sword < 10:
print("You have died!")
D20 = randint(1,20)
Adventurer = Hero
#Adventurer.D20_Func() Ignore this...aborted effort to try something
Adventurer.swing_and_hit(sword, D20)
Every time I run this at http://pythontutor.com/visualize.html#mode=edit, the random number generator outputs 13. I cannot figure out why it does this...any thoughts? I have tried nesting the random number generation inside the function swing_and_hit, and it still generates the same number every time I run the program.
This seems to be a "feature" in Pythontutor to ensure different people will see the same results running the same code. (I am getting always 17)
Whether or not they define it as a feature, it is broken as it could be - random numbers should be random.
Just install Python in your own computer, and get going - it is a smaller than 20MB download from http://python.org if you are using Windows (and if you are not, you have Python installed already). There are interactive interpreters and even a simple development environment that is installed along with the language - there is no motive for you to hurt yourself with a web implementation that might be good for group study of some code, or introspecting what goes in each variable step by step. Python interactive environments are much more dynamic than the "click to run" you get on this site.
I think the random number generator producing the same number every time is a quirk of pythontutor.com. I get 17 every time with just this code:
import random
print(random.randint(1, 20))
If you must use a website to run your code, try repl.it.

Fortune cookie game in Python

This is I'm sure a fairly rudimentary questions involving Python, but I've only recently started using the program. Here is the challenge:
"Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it's run."
My approach was to assign five distinct variables their own individual fortunes:
fortune_1 = str("Good things come to those who wait.")
fortune_2 = str("Patience is a virtue.")
fortune_3 = str("The early bird gets the worm.")
fortune_4 = str("A wise man once said, everything in its own time and place.")
fortune_5 = str("Fortune cookies rarely share fortunes.")
What I am not clear on is how to generate the fortunes at random. Is there a way to utilize the random. module to pick one of the five predetermined fortunes uniquely each time? For example, could I set those five fortunes as numbers and then say something like:
user_fortune = random.randfortune(1,5)
? I hope this makes sense. As I am new to Python and posting in this forum it may take me some time to communicate more clearly.
Thanks!
My first instinct was to tell you to put your fortunes into a sequence of some kind (e.g., list, tuple). Then, you just need to pick a random element. I did the following at the Python prompt:
>>> import random
>>> help(random)
Help on module random:
NAME
random - Random variable generators.
FILE
/usr/lib/python2.7/random.py
MODULE DOCS
http://docs.python.org/library/random
DESCRIPTION
integers
--------
uniform within range
sequences
---------
**pick random element**
pick random sample
generate random permutation
distributions on the real line:
Aha! "pick random element" sounds good. So, I keep scrolling:
| **choice**(self, seq)
| Choose a random element from a non-empty sequence.
|
Aha again! I suppose I should have just known this, but it's good to know how to look this stuff up when you need it.
Possible solution (Python 2.7):
import random
fortunes = ["Good things come to those who wait.",
"Patience is a virtue.",
"The early bird gets the worm.",
"A wise man once said, everything in its own time and place.",
"Fortune cookies rarely share fortunes."]
print random.choice(fortunes)
You can add the fortunes to a list and select a random item from the list using choice:
import random
fortunes = [fortune_1, fortune_2, fortune_3, fortune_4, fortune_5]
print random.choice(fortunes)
Thank you very much!
I also noticed that I could try the following:
import random
fortune = random.randint(1,5)
if fortune == 1:
print("Good things come to those who wait.")
elif fortune == 2:
print("Patience is a virtue.")
elif fortune == 3:
print("The early bird gets the worm.")
elif fortune == 4:
print("A wise man once said, everything in its own time and place.")
elif fortune == 5:
print("Fortune cookies rarely share fortunes.")
imort random
fortune_cookie = random.choice([""Good things come to those who wait.",
"Patience is a virtue.",
"The early bird gets the worm.",
"A wise man once said, everything in its own time and place.",
"Fortune cookies rarely share fortunes."])
print(fortune_cookie)

Why is my program ending early?

I was recently able to get this to run thanks to all of your help, but I cant figure out why my program is ending here. Looking at it, if answer == 3: should just bring you to the next encounter, but my program is closing. Am I missing something?
# First Encounter (main program really)
def fi_en():
global pow, cun, per
print"""
It smells of damp vegetation, and the air is particularly thick. You can
hear some small animals in the distance. This was a nice place to sleep.
1. Stay close, find some cover, and wait for food to show up.
2. Explore the nearby marsh & find the nearest river, following it downstream.
3. Walk towards the large mysterious mountain in the distance.
"""
answer = int(raw_input(prompt))
if answer == 1:
cun_one = roll_3d6()
if cun_one <= cun - 2:
print"""Time passes as eventually you capture some varmints.
You feel slightly more roguish."""
cun = cun + 1
fi_en()
else:
print """Time passes and a group of slavers marches into right
where you are hiding in the woods. They locate you, capture you, and haul you
away for a lifetime of servitude in the main city.
Goodbye %s""" % name
elif answer == 2:
power = roll_3d6()
if power <= pow - 4:
print"""You trudge through the marshes until you eventually reach
a large river. Downstream from the river is a large temple covered in vines,
you walk towards it. You feel more powerful."""
pow = pow + 2
te_en()
else:
print """The vegetation here wraps itself around your legs making
it impossible to move. You will most likely die here in the vegetation.
Goodbye %s.""" % name
elif answer == 3:
cun_two = roll_3d6()
if cun_two <= cun:
print """You make your way towards the mountain and you encounter
a really large group of devil dogs guarding the entrance to the mountain."""
dd_en()
else:
print"You have gotten lost and ended up right where you started."
fi_en()
And my output is:
It smells of damp vegetation, and the air is particularly thick. You can
hear some small animals in the distance. This was a nice place to sleep.
1. Stay close, find some cover, and wait for food to show up.
2. Explore the nearby marsh & find the nearest river, following it downstream."
3. Walk towards the large mysterious mountain in the distance.
> 3
Raymond-Weisss-MacBook-Pro:lod Raylug$
It sounds to me like you're missing a really large group of devil dogs. Are you sure you want to fix this?
You haven't defined your globals anywhere. You have no "else" statement within condition three, so since cun_one is not less than/equal to your undefined cun variable, there is nothing else to do when answer == 3.
Deleted everything since you already got it working, just a comment.
You can use input('Prompt') since it automatically becomes an int, raw_input converts the input to a string, and then you are converting that string to an int, which is unnecessary.

Categories