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.
Related
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.
Im writing a text game and all other parts of my code are working i think but ive been trying to figure out why my variable isnt defined.
I could be missing something simple but i just cant find it.The problem is under def aussie().
Ive tried changing indents, changing variable name and checking for " or () missing/
def aussie():
home= input("""
'Where are you from? it'd be better off taking you home than you travelling with us
A)Ortus
B)...""")
if "A" in home:
print("""
Eugene says 'How the hell did you end up out here then?You know what doesnt matter'
They take you back home to Ortus.
You Win""")
start()
if "B" in home:
print("""
Eugene says 'Right then guess your coming back to Australia with us!'
You live happily ever after with Eugene
You Win?!""")
start()
def boat():
h= input("How will you get help?")
if "swim" in h:
print("""
The boat goes right past you leaving you stranded.
You Lose""")
start()
if "shout" in h:
print("""
One of the crew members hear you and shout orders to slow the boat.You notice he has a
very strong Australian accent. The crew help you onto the boat wrapping you in towels
and blankets before sitting you at a table.You are in a state of shock.
You try to stand up but feel nauseous and dizzy.You fall to the floor with a thud.
The same Australian man rushes in and props you up against a wall before sitting next
to you on the floor.He sits for a while and chats to you letting you know his name is Eugene.
When you feel better he asks,""")
aussie()
start()
direct()
Your indentation is wrong. You must be very careful with indentation in Python Because start() is in column 1, it is no longer considered part of the function. It will be executed immediately. You might consider storing your very long strings in a global array up at the top, to make the indentation more obvious.
And, by the way, if start ends up calling aussie or boat, then you have recursion going on. That is NOT a good way to design something like this. These functions should return True or False telling the caller whether they should loop around again or exit.
I have a question on this code im trying to write. It says an error with "NameError: name 'answer' is not defined on line 1". Can someone point out what is wrong?
def main():
answer = input("Would you like to play a game? yes or no")
if (answer == "yes"):
firstChoice = input(
"There was once a knight, stuck in a forest trying to look for a princess. The knight had 2 ways he could go. Should he go left, or right?"
)
if (answer == "left"):
secondChoice = input(
"He decides to go left. As he passes the trees, he sees something he hasn’t seen before. A GIANT DRAGON! He pulls out one of his weapons. Which weapon did he pull out? Oversized Sword or Flamethrower?"
)
if (answer == "mighty sword"):
thirdChoice = input("He pulls out his mighty weapon. It was about as tall as a bus! The dragon said, Wait, just the size of a bus? I’m like, 200 buses. The knight, realizing that his choice was stupid, got the heck out of there! The dragon, being the 200 buses that he is, couldn’t find the puny mortal. He decided to brush it off and went to his dome. The poor knight, out of breath, gets a drink of water from a creek. The knight says, Wait, I know this creek! This is the Golden Creek, so if I follow this path, the dome should be right there! The knight decides to go with his gut and follow the path. And before he knows it, the princess was trapped inside of the dragon’s dome! He knew he had to do something, but what? Should he sneak in, or barge in alone?")
if (answer == "sneak in"):
print("He tries to sneak in. Getting past every dragon guard, was surprisingly easy. Their eyes are on the side of their head, so if you just walk in front of them, you should be good. Luckily, when the knight came, the dragon was asleep. He needed crucial silence, where not the single creek of wood, or cling of the armor could wake up the dragon. The knight whispers to the princess, I have come to save you! The princess carefully follows the brave knight, and they make it out! The king is happy with your success in keeping the princess alive, and you are promoted to secretary, the highest rank below the king! YOU WIN")
This is a scope error. You initalize answer in your main method, however as soon as that method closes, the variable is deleted. The 3 if statements do not have access to this variable.
First, you don't need to use the parenthesis in the if statements. The error is likely caused by not using a tab when you define the function.
Sorry about suggesting an IDE, don't know how you could have copy and pasted the text...
Without running your code, i can see a big problem, you may want to try this
After each input tag, you say "if answer =="
But remember, the answer variable is going to be the first thing the user inputted
so if they put "yes" the answer variable will always be "yes" throughout the entire script unless you redefine it
EDIT
When i first answered, the post was not entirely in the code block so i couldn't see the indentation
The variable answer is only within main() to use it outside of main() you should define it globally, meaning before the main function
Actually, you just need to use global before the declaration.
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)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I found this problem, which I thought would be interesting to solve but couldn't really come up with a correct solution-
Inside a room, there is a monster with
N heads, and a human (with 1 head).
The human has two laser guns. The
first gun, A destroys C1 heads when
fired and the second gun,B destroys C2
heads when fired [The guns may destroy
both the monster's as well as human
heads, but the guns prioritize monster
heads over human ones].
Also, if after the firing of the gun
the monster has a positive non-zero
number of heads left, the monster will
grow additional heads. The monster
grows G1 heads when gun A is used and
it grows G2 heads when gun B is used.
The problem is to input N, C1, C2, G1
and G2, then find out what would be
the shortest combination of
gun-choice(A or B) the human must use
to kill the monster(the monster dies
when No. of heads=0).
[Note- this problem is from a programming contest that has already ended]
I tried approaching this problem using recursion but found myself clueless about how to actually come up with the solution. So, if you could give some hints how to approach the problem, that'd be great.
First of all: Dijkstra's is not the optimal solution :)
Given this sentence: "The guns may destroy both the monster's as well as human heads"
I take it if you can shoot 10 heads and the monster only has 5 heads, you can't kill it because that would kill you too. Is that correct?
In any case, any solution would be of the form:
ABABAABBABBB... (some string of A's and B's)
On the final hit you kill C1 or C2 heads. On every other hit you kill C1 - G1 or C2 - G2 heads.
If the final hit is from A, you have to destroy N-A heads with shots doing (C1-G1) or (C2-G2) damage.
If the final hit is from B, you have to destroy N-B heads with shots doing (C1-G1) or (C2-G2) damage.
Any K can be represented in the form:
X*i + Y*j = K
Of course, X and Y have to be coprime, etc.
K heads can be destroyed by i shots of damage X and j shots of damage Y.
You can find out the values of i and j with the extended greatest common divisor algorithm.
Solve for X = (C1-G1), Y = (C2-G2) and K = (N-A)
Also solve for X = (C1-G1), Y = (C2-G2) and K = (N-B)
The smallest answer is the correct one :)
That's it :)
Ah, I see you have found a solution in C++ already using Dijkstra's algorithm: http://hashsamrat.blogspot.com/2010/10/surviving-monster-programming-problem.html
However, you seem to be thinking about 'recursion' and other methods.
The solution is separate than the implementation. Thus what you really want to do would be to use the same algorithm (Dijkstra's, which is just breadth-first search carefully done so you visit the shortest paths first), but in python rather than C++.
You could just copy the C++ line-by-line, using python idioms to make the code cleaner and more elegant. But you'll still be using the same algorithm. (Alternatively, you could Google for the hundreds of ways people have implemented Dijkstra's in python. Or you could write it yourself; all you need is a priority queue (see wikipedia), and if time isn't an issue, you can write a poorly-performing priority queue in the form of a dictionary-of-lists.)
edit: Thinking about it, if by "shortest set of choices" you just mean "fewest gunshots", you don't really need Dijkstra's at all; it's just breadth-first-search (which is equivalent to Dijkstra's when all edges have weight 1).
In particular, the logic to generate a new node is as follows:
def howManyHeadsLeft(currentHeads, damage, regen):
newHeads = heads - damage
if {this results in blowing off our own head} and newHeads>0: #modify depending on assumptions
# we killed ourselves without taking monster down with us
return {} # the empty set of possible search nodes
else:
newHeads += regen
# we could just say return {newHeads} here,
# but that would be terribly slow to keep on searching the same
# state over and over again, so we use a cache to avoid doing that
# this is called dynamic programming
if {we have never seen newHeads before}:
return {newHeads}
else
return {}
def newSearchNodes(currentHeads):
return howManyHeadsLeft(currentHeads, atypeDamage, atypeRegen) | howManyHeadsLeft(currentHeads, btypeDamage, btypeRegen)
The 'goal' condition for the search is having just enough damage to kill the hydra without killing yourself (modify as appropriate depending on assumptions):
heads==1+atypeDamage or heads==1+btypeDamage
Of course it is also possible that no solution exists (regen > damage for both types of guns), in which case this algorithm might run forever, but could probably be modified to terminate.