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.
Related
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?
#Variables
enemy=['Dummy','Ghost','Warrior','Zombie','Skeleton']
current_enemy=random.choice(enemy)
enemy_health=randint(1,100)
dmg=randint(0,50)
current_enemy_health=enemy_health-dmg
#Functions
def enemy_stats(current_enemy_health):
if current_enemy_health<=0:
print(current_enemy,"died.")
if current_enemy_health>0:
dmg=randint(0,50)
current_enemy_health=enemy_health-dmg
print(current_enemy,"has",current_enemy_health,"health left.")
#Meeting an enemy - Attack / Defend Option
def encounter(current_enemy):
print(name,"encountered a",current_enemy,"with",current_enemy_health,"health.","What do you do?")
print("Attack? or Defend?")
def battle():
encounter(current_enemy)
#Attack Or Defend?
choice=input("What do you do?")
if choice!="Attack" or choice!="Defend": #If the choice isn't attack then ask again
print("Do you attack or defend?")
choice=input("What do you do?")
#Say correct sentence depending on what you do.
if choice=="Attack": #If the choice was attack then do a random number of dmg to it
print(name,choice+"s",current_enemy,".","You deal",dmg,"damage","to it.")
enemy_stats(current_enemy_health)
if choice=="Defend": #If ... to it
print(name,choice+"s.")
#Check to see if the enemy is still alive
while current_enemy_health>1:
#Attack Or Defend?
choice=input("What do you do?")
if choice!="Attack" or choice!="Defend": #If the choice isn't attack then ask again
print("Do you attack or defend?")
choice=input("What do you do?")
#Say correct sentence depending on what you do
if choice=="Attack": #If the choice was attack then do a random number of dmg to it
print(name,choice+"s",current_enemy,".","You deal",dmg,"damage","to it.")
enemy_stats(current_enemy_health)
if choice=="Defend": #If ... to it
print(name,choice+"s.")
#Checks to see if the enemy is dead
if current_enemy_health<=0:
print(name,"successfully killed a",current_enemy)
battle(
)
So i'm making a text-based RPG game. All going well but there is one thing I can't fix, i've tried a lot of things to try and fix the problem, basically when you encounter and enemy it spawns with a random amount of health. You then hit it for some damage. 'Zombie with 20 health spawned. What will you do?' I attack and say I deal 9 damage. What happens is that the health just goes to a random number instead of 20-9. Or say I did 21 damages. What happens this time is that the health once again goes to a random number instead of 20-21 and dieing. Basically what I can't manage to fix is the health-dmg part. I haven't managed to see if the health<0 works as I can never get the enemy to 0 health.
Any help would be appreciated.
In your function:
def enemy_stats(current_enemy_health):
if current_enemy_health<=0:
print(current_enemy,"died.")
if current_enemy_health>0:
dmg=randint(0,50)
current_enemy_health=enemy_health-dmg
print(current_enemy,"has",current_enemy_health,"health left.")
You have these two lines:
dmg=randint(0,50)
current_enemy_health=enemy_health-dmg
What this essentially does is subtract a random number from the current health of the enemy, which would result in the random number you reported having. To fix this, have whatever weapon a player is using be assigned a "damage" that it does that and put that into the function as an argument. Your new function would look like this:
def enemy_stats(current_enemy_health, dmg):
if current_enemy_health<=0:
print(current_enemy,"died.")
elif current_enemy_health>0:
current_enemy_health=enemy_health-dmg
print(current_enemy,"has",current_enemy_health,"health left.")
And would be implemented like this:
enemy_stats(var_for_current_enemy_health, damage_of_weapon)
Best of luck, and happy coding!
I'm totally new to Python and programming in general, and just starting to learn how to crawl, basically. I decided to learn programming by doing, and so I tried to develop a little dice game.
The main intention (i did not manage to succeed in making the code like i wanted it to) was to make a game with the following rules:
The game is played by two or more players
There is only one dice involved in the game
Object of the game is to be the first to get at least 100 points
A player is chosen by random to go first: The player can roll the dice as many times as s/he likes, and the points are accumulated. However, if the dice returns 1, the player loses the accumulated points. At any time, the player can choose to stop rolling the dice and secure the points. By doing this, the player loses its turn, and the next player can start rolling. Points that are secured, can never be lost.
When first trying to make this code, I wanted to make it with classes and functions, but I just couldn't make that work. Also I couldn't figure out how to design the game for multiple players. I tried working with lists and dictionaries, but I just kept pulling my hair. So I just tried to make the game for 1 player, where the objective is to reach a 100 points in fewest rounds (a new round starts everytime you secure points). Not very fun, but at least I got it to work (well, sort of).
I would highly appreciate any comments to my little program. Please note it's my first code, and I know it is really badly written. I want to hear how you guys think the code could be improved, and how I should go about in organizing the code for multiple players. I'm interested in learning to program for mobile devices at a later stage, and want to eventually turn this little game into an app so I can play with friends (for fun and as a way to learn the how-to's).
Hope the indents are adjusted properly.
from random import choice # Importing the random element to create the dice
score = 0
rounds = 1
secured = 0
unsecured = 0
ask = "N/A"
while secured+unsecured < 100: # Check if the total score is below 100
a = int(choice([1,2,3,4,5,6])) # Choose a dice number
if a == 1: # Check if the dice is one
if ask == "s": # Check if the player secured the last score
print ("Good thing you just secured your score, because you now rolled a 1.")
print ("Because of this, you only lost your round, not any points! :)")
if ask =="N/A": # Check if the player rolled a one on the first throw
print ("************* Round 1 ***********")
print ("Tough luck, you rolled a ONE on your first roll. You lost one round.")
rounds +=1
if ask == "r": # Check if the player lost points that was unsecured
print ("")
print ("***** UH UH UH UH UH - YO ROLLED A ONE ******")
print ("You lost the", unsecured,"points you didn't secure")
unsecured = 0 # Player loses the unsecured points
rounds +=1 # Increase round number
else:
unsecured = unsecured + a # If the dice returned something else than one, the player wins the points
print ("")
print ("")
print ("************ Round ", rounds, "**************")
print ("")
if a > 1: # Only display the dice if the dice is higher than one (if it's one it has already been printed)
print ("You rolled a ", a)
print ("")
print ("Unsecured points: ", unsecured)
print ("Secured points:" , secured)
print ("The sum of secured and unsecured pointsare:",secured+unsecured, "points")
print ("")
ask = input ("Roll the dice or secure? (r/s) ")
if ask == "s":
secured = secured+unsecured # If player chooses to secure the points, the points are added
score = 0
rounds +=1 # Increase round
if unsecured == 0: # Check if player was an idiot and chose to secure 0 points
print ("You chose to secure zero points, not very clever! You wouldn't risk anything by rolling the dice, and you lost the round!")
else:
print ("You chose to secure your", unsecured, "points, and you have secured", secured, "points in total")
print ("")
unsecured = 0 # Reset unsecured points, since it is added to secure points
input ("Press Enter to roll the dice:")
else:
if ask == "r":
score = unsecured+a
else:
print ("Congrats! You made ",secured+unsecured, "points in", rounds , "rounds")
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!
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.