randint usage in Learn Python the hard way exercise 43 - python

I am having trouble with the randint usage of exercise 43 in Learn python the hard way link to exercise. Assuming I follow Zed Shaw's code perfectly in all other parts of the program, and I have from random import randint, when I run the program and type the 3 digit passcode into the keypad, it returns a "BZZZZEDDD!". Here is that section of code:
class LaserWeaponArmory(Scene):
def enter(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It's dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There's a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can't"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return 'the_bridge'
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return 'death'
Lets say in the guess = raw_input("[keypad]> ") when running the program I type in "368".
Shouldn't that be within the parameters of code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) and be TRUE for if guess ==code:? Instead it runs it as if guess != code and returns a "BZZZZEDDD!"

Your guess of 368 is within the possible range for the code, but that's not what the while loop is checking. The line
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
will generate a string of three random digits. The code could be anything between 111 and 999 (except there can be no zeroes) and you have no way of knowing exactly what it is as the program currently stands. At the bottom of the lesson, under Study Drills, the author says:
Add cheat codes to the game so you can get past the more difficult
rooms. I can do this with two words on one line.
Presumably, this code is one of the rooms he's talking about. Try adding something that will give you a hint of the code.

Related

Can't figure out how to have percentage chnnances for something to happen

I am making a text-based game; I am trying to figure out a way to have multiple endings and certain percentages for each to happen, but when I run this, it comes up with weird letters and sometimes multiple endings.
choice1_wakeup = input ("Wake Up? Y or N:")
if choice1_wakeup == 'y' or choice1_wakeup == 'Y':
print ("Placeholder")
else:
import random
for x in range(100):
ending_percent = (random.randint(1,10))
if ending_percent > 2:
choice1_ending_common = ("You are woken a while later and see the priest holding a knife to your throat for a moment before he slits it and you bleed out.")
print (random.choice(choice1_ending_common))
elif ending_percent < 2 and ending_percent >0.5:
choice1_ending_rare = ("You wake up a little while later and find yourself dangling over the mouth of the sacrificial volcano while your tribe chants the name of the fire goddess, kahuahuahua, kahuahuahua, kahuahuahua. “What’s happening?” you ask the priest. “You are being sacrificed for your crimes” he replies and at that he tosses you into the fiery abyss.","A few minutes later you are woken by the suddenly extremely cold temperatures. You look around and spot the god of death daharasus. “Why haven’t you completed your rituals to me yet?” he asks you in a stone cold voice. “I’m sorry, I fell asleep” you frightendly reply. “I don’t want excuses!” he screams, he levels his finger at you and you are instantly killed, your soul is forever trapped in the same spot reliving that moment over and over forever.")
print (random.choice(choice1_ending_rare))
else:
choice1_ending_impossible = input ('You are woken up by a stranger a few hours later. "Who are you?" you ask the strange man standing over you. "My name is Jeff Probst" he replies. "I was wondering if you would like to be on my new TV show?" Y or N:')
if choice1_ending_impossible >= 'y' or choice1_ending_impossible >= 'Y':
print ("impossible test")
Please read the documentation for the choice method. That method picks a random element from the iterable sequence you give it. In this case, the sequence you provide is the text of a single ending. The available choices are the individual letters of that ending, so ... you get a single, random character.
If you want to choose a random text, you need to give it a list of strings, such as
ending_list = [
["You and your team vote Jeff Probst off the island.",
"You eat five ugly things and win the immunity challenge.",
"The show is canceled for lack of geologically stable shooting locations."]
Now you can pick one element from ending_list. Is that enough to get you going?

updating a global list python

Full disclosure -- this is my first stack overflow question. I searched around for a similar question for awhile but couldn't find one that helped me given my limited scope of knowledge (there were python global variable questions but the answers given were over my head).
I'm new to programming and i'm learning python via python the hard way by Zed Shaw. I'm on exercise36 and my goal is to write my own text based game.
The game starts with the following function
def start():
global Your_HP
Your_HP = 20
global Your_Ammo
Your_Ammo = 20
global HP_Scan
HP_Scan = 2
global your_stats
your_stats = [Your_HP, Your_Ammo, HP_Scan]
print "You enter a room with two doors"
print "Do you choose the Red Door\n...or the Blue door?"
start_choice = raw_input("> ")
if "red" or "Red" in start_choice:
monster_HP = 2
monster_attack = 3
red_one(your_stats, monster_attack, monster_HP)
The red_one function looks like this:
def red_one(your_stats, monster_attack, monster_HP):
print "Immediately you notice a monster in the room"
print "You point your rifle at the monster before you"
shoot(Your_Ammo, monster_HP)
if monster_HP <= 0:
print "You killed it!"
print "You now have %d bullets left" % Your_Ammo
print "You finally look around the room"
print "There is a door going straight"
print "There is a door going left"
room_choose()
elif monster_HP > 0:
print "The monster has %d HP" % monster_HP
print "He stumbles, but not dead!"
print "He shoots back at you with his lil pistol!"
get_shot(monster_attack, Your_HP)
else:
dead('just because')
The script immediately runs the shoot function which looks like:
def shoot(Your_Ammo, monster_HP):
print "---------"
print "You have %d HP left" % Your_HP
print "How many shots do you fire?"
shots_fired = raw_input('> ')
shots_fired = int(shots_fired)
Your_Ammo -= shots_fired
monster_HP -= shots_fired
return Your_Ammo, monster_HP
The problem is that when I run the script and shoot only 1 time, when I return to the start of red_one, the Your_Ammo and monster_HP variables revert to their original values instead of the updated one i'm returning from shoot
I've tried moving where I'm declaring the global variables (initially declaring outside of all functions instead of in start) and I just get an "x variable is local and global" error.
I know global variables in general are not always the best idea, so I'm just hoping someone can break this down for me in an elegant way and provide a helpful solution, regardless of whether or not it includes a global variable.
Ideally, I'd like to update the variables in the your_stats list throughout the course of the game. Essentially, from any function in the game, I want to be able to return any variable within the your_stats list so I can use that variable as an argument for other functions until the player runs out of HP or ammo.
Sorry this post was a bit verbose! Any help is really appreciated!

Beginner Python: How to give different responses to ELSE in a while-loop

So, I'm working my way through Learn Python the Hard Way, and I am on Lesson 36, where I make my own BBS-text-style game based on the one he did in lesson 35.
http://learnpythonthehardway.org/book/ex36.html
http://learnpythonthehardway.org/book/ex35.html
So, I did a decent job, but I noticed that when I mimicked his eternal while-loop, where the player can't ever leave the room under anything but very specific circumstances, the loop always gives the same response for the else...unless they say the right thing, they're stuck forever.
Here's my code:
def sleeping_giant():
print "There is a single door, with a giant sleeping in front of it."
print "How can you get the giant to move?"
print "Should you wake him?"
giant_moved = False
while True:
choice = raw_input("> ")
if choice == "Yes":
dead("The giant rips you into four pieces and uses your quartered body as a stack of pillows.")
elif choice == "No" and not giant_moved:
print "The giant rolls in his sleep, clearing an easy path to the door."
giant_moved = True
elif "Open" or "Go" in choice and giant_moved:
treasure_room()
else:
print "I have no idea what the fuck you are trying to say to me. English. Do you speak it?!"
Apologies if that format doesn't translate well.
Anyway, anytime the user types something that doesn't satisfy an if or an elif, they will receive that same else response.
How would I change this? As in, make it more dynamic, so that if they keep screwing up the response, the else response changes?
I can't figure out how to get the code to say (in non-literal terms, I mean, I can't get the logic to say), 'If the else has been used, the response should be a new else, and once that one has been used, it should be yet another else response'.
If this doesn't make sense, please let me know.
Here's the incremental version of Greg's answer using a counter so you can get a predictable order of responses:
global responses = [ "Nice try. Try again.",
"Sorry, what was that?",
"I don't know what that means."]
def sleeping_giant():
counter = 0
print "There is a single door, with a giant sleeping in front of it."
print "How can you get the giant to move?"
print "Should you wake him?"
giant_moved = False
while True:
choice = raw_input("> ")
if choice == "Yes":
dead("The giant rips you into four pieces and uses your quartered body as a stack of pillows.")
elif choice == "No" and not giant_moved:
print "The giant rolls in his sleep, clearing an easy path to the door."
giant_moved = True
elif ("Open" in choice or "Go" in choice) and giant_moved:
treasure_room()
else:
print responses[counter]
if counter < 2:
counter += 1
This condition:
elif "Open" or "Go" in choice and giant_moved:
parses as the following (according to operator precedence):
elif "Open" or (("Go" in choice) and giant_moved):
Since "Open" is considered True, this condition will always match. It sounds like you might instead want:
elif ("Open" in choice or "Go" in choice) and giant_moved:
To choose a different response, try something like:
else:
responses = [
"Nice try. Try again.",
"Sorry, what was that?",
"I don't know what that means.",
]
print random.choice(responses)

Python beginner, text-based game

I'm fairly new to the programming game; I'm 3/4 of the way through Learn Python the Hard Way and I had a question about a little text-based game I made... So in this game my guy is stranded on a desert island and you have the option(raw input) of going left right or into the jungle. After choosing a direction, you're given the option to choose how many miles to walk. Each direction is supposed to have a different end result (and mile distance).
If you enter a number that is less than the number of miles to the destination, you're prompted with a choice to either "turn around or "keep going". If you enter turn around, you're taken back to the beginning, where you're again asked to choose a direction. If you enter keep going, the program returns to miles(), where you can choose a new amount of miles to walk.
def miles():
print "How many miles do you walk?"
miles_choice = raw_input("> ")
how_much = int(miles_choice)
if how_much >= 10:
right_dest()
elif how_much < 10:
turn()
else:
print "You can't just stand here..."
miles()
Ok so here's two questions:
How would I make it so that if the user originally enters a number of miles less than the destination distance, and the second mile input + the first mile input == the amount of miles to the destination, it will add the inputs and run my destination function, not just repeat miles().
Since all three final destinations will have different distances, should I write three separate mile functions? Is there a way to make it so that depending on the original direction chosen, miles() will run the different endpoints?
I'm sorry if this doesn't make a lick of sense... I'm still learning and I'm not sure how to fully explain what I'm trying to get across.
You could store the amount of miles to walk in each direction in a dict, and then check the dict to see if the user has walked far enough:
distances = {
'right': 7,
'left': 17,
'forward': 4
}
direction_choice = raw_input("> ")
miles_choice = raw_input("> ")
if how_much >= distances['direction_choice']:
right_dest()
elif how_much < distances['direction_choice']:
turn()
else:
print "You can't just stand here..."
miles()
Be sure to properly validate and cast the user input, which I have not addressed. Good luck!
I don't fully understand the requirements (the intended behavior and constraints). However, you might consider passing a parameter to your function (through and argument) to convey the maximum number of miles which the play could go in that direction).
For example:
#!/usr/bin/env python
# ...
def miles(max_miles=10):
print "How many miles do you walk?"
while True:
miles_choice = raw_input("> ")
try:
how_much = int(miles_choice)
except ValueError, e:
print >> sys.stderr, "That wasn't a valid entry: %s" % e
continue
if max_miles > how_much > 0:
break
else:
print "That's either too far or makes no sense"
return how_much
... in this case you pass maximum valid number of miles into the function through the "max_miles" argument and you return a valid integer (between 1 and max_miles) back.
It would be the responsibility of this function's caller to then call right_dest() or turn() as appropriate.
Note that I've removed your recursive call to miles() and replace it with a while True: loop, around a try: ... except ValueError: ... validation loop. That's more appropriate than recursion in this case. The code does a break out of the loop when the value of how_much is valid.
(By the way, if you call miles() with no parameter then the argument will be set to 10 as per the "defaulted argument" feature. That's unusual to Python (and Ruby) ... but basically makes the argument optional for cases where there's a sensible default value).
#Question #1: I used Class intern variables. You will maybe need them for further programming parts and should take it to zero when you are done on one direction, to start with zero for next step/lvl.
#Question #2: Dictionaries are the best way to do so,self.dest. Parameter pos used as key to get the value from the dictionary.
class MyGame:
def __init__(self):
self.current_miles = 0
self.dest = {'Left' : 10, 'Into the jungle' : 7, 'Right' : 22}
def miles(self,pos):
print "How many miles do you walk?"
miles_choice = raw_input("> ")
self.current_miles += int(miles_choice)
if self.current_miles >= self.dest.get(pos):
self.miles("Right")
elif self.current_miles < self.dest.get(pos):
print "you went "+ str(self.current_miles) + " miles"
else:
print "You can't just stand here..."
self.miles(pos)
mg = MyGame()
mg.miles('Into the jungle')

Creating a while loop for a Game

I am new to Python and I had a quick question about a code I have been working on today. I am creating a game that uses a while loop where the two opponents will have turns to "hit" one another until one of the players have 0 health points.
This is the code I have so far, although it is not working. Can anyone help?
done=False
while not done:
if You.Hit_points>Opponent.Hit_points:
move=raw_input("Would you like to make a move? (y/n) ")
if move=="y":
print "",You.name,"hit ",Opponent.name," by",You.Hit_points," hit points!"
Opponent.Health=You.Hit_points+You.Skill_points+Opponent.Health
print "Due to the hit",Opponent.name,"is left with",Opponent.Health," health points."
print ("The Mighty Beast will make a move.")
print "",Opponent.name,"hits",You.name,"by",Opponent.Hit_points,"points"
You.Health=(Opponent.Hit_points-Opponent.Skill_points)+You.Health
print "Due to the hit",You.name,"loses",Opponent.Hit_points,"points.Leaving",You.name,"with",You.Health,"health points."
print "Now it is",Opponent.name,"'s turn to make a move"
You.Health=You.Health-(Opponent.Hit_points+Opponent.Skill_points)
print "Due to the hit",You.name,"is left with",You.Health,"health points."
else:
You.Hit_points==0
move=="n"
done=True
if You.Hit_points>Opponent.Hit_points:
should probably be
if You.Hit_points > 0 and Opponent.Hit_points > 0
right? Otherwise as soon as You's HP drops below Opponent's--which could be after the first turn--the fight will end.

Categories