RPG Battle, monsters health after attack with dictionaries - python

I've asked about this before, because I'm still not too familiar with dictionaries, but what's happening is every time I attack the monsters health resets automatically:
#MONSTER STATS
corpsefinder_stats = {
"corpsefinder_strength" : 7,
"corpsefinder_speed" : 1,
"corpsefinder_mana" : 0,
"corpsefinder_health" : 45,
}
#GAME START
if game_start==True:
time.sleep(0.6)
print(username, "wakes up, the cold snow on their face as they lie down in bewilderment, wondering where they could of come from and why they are here. As they stand up, they notice a small village in the distance, but before they can even begin to think of venturing over, a small bug-like creature approaches, primed for battle")
time.sleep(8)
while corpsefinder_stats["corpsefinder_health"] >= 1 or health >= 1:
tutorialbattle=input("\nA CORPSE-FINDER gets ready to attack!\nWhat will you do?\n\n##########\n# Attack #\n##########\n\n##########\n# Defend #\n##########\n")
tutorialbattle=tutorialbattle.lower()
if tutorialbattle=="attack":
corpsefinder_stats["corpsefinder_health"] -(random.randint(strength-10, strength))
print(username, " attack!\nCORPSE-FINDER HP: ", corpsefinder_stats["corpsefinder_health"])
print("CORPSE-FINDER attacks!\n", username, " HP: ", health-(random.randint(corpsefinder_stats["corpsefinder_strength"]-6, corpsefinder_stats["corpsefinder_stren

When you do :
corpsefinder_stats["corpsefinder_health"] -(random.randint(strength-10, strength))
you are just performing the mathematical operation, not assigning it to anything.
You need to do :
corpsefinder_stats["corpsefinder_health"] = corpsefinder_stats["corpsefinder_health"] -(random.randint(strength-10, strength))

Related

Combat sequence for a text-based RPG

This is the code.
#When I try to make the variable ‘enemy’ save globally, it says ‘Variable referenced before assignment.’, or something along those lines. How do I fix this?
#If you are going to suggest to make it all one function, I tried and it didn't work out. I am doing this so I can keep repeating the turn function until the player enters a vaild command.
#Player and enemy stat blocks. Order of stat blocks is: Health, Weapon, Weapon damage, Armor, and Armor type.
PC = [50, 'shortsword', 20, 'chain mail', 10]
goblin = [30, 'dagger', 15, 'leather', 5]
# Function for a single turn.
def turn(enemy):
turn1 = input('Your turn. What would you like to do? ').lower()
if turn1 != 'attack':
print('Invalid command.')
turn(enemy)
elif turn == 'attack':
global enemy
enemy[0] = enemy[0] - PC[2]
# Function for the entirety of combat.
def combat(enemy):
while enemy[0] > 0:
turn1 = input('Your turn. What would you like to do?')
turn(enemy)
combat(goblin)

The script is not assigning points to the attribute

I'm trying to create a text-based adventure game and all is going well until I encountered a problem with assigning points to attributes. I've been using this website to help with the process but realized that it might be in Python 2. Here's all that I've done so far code:
#Date started: 3/13/2018
#Description: text-based adventure game
import random
import time
def display_intro():
print('It is the end of a 100-year war between good and evil that had \n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n' +
'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n' +
'wed and had you. \n')
time.sleep(3)
def get_gender(gen=None):
while gen == None: # input validation
gen = input('\nYour mother had a [Boy or Girl]: ')
return gen
def get_name(name = None):
while name == None:
name = input("\nAnd they named you: ")
return name
def main():
display_intro()
gender_num = get_gender()
charater_name = get_name()
print("You entered {} {}.".format(gender_num, charater_name))
if __name__ == "__main__":
main()
character_name = get_name()
# Assignning points Main
my_character = {'name': character_name, 'strength': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
#This is a sequence establises base stats.
def start_stat():
print("\nThis is the most important part of the intro\n")
time.sleep(3)
print("This decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category:
Strength, Health, Wisdom, or Dexterity.\n")
def add_charater_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much?"))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
else:
print("That attribute doesn't exist!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_charater_points()
else:
display_intro()
gender_num = get_gender()
charater_name = get_name()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_charater_points()
elif choice == "2":
pass
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
And here's what happens when I run it:
It is the end of a 100-year war between good and evil that had
killed more than 80% of the total human population.
The man who will soon be your father was a brave adventurer who fought for
the good and was made famous for his heroism.
One day that brave adventurer meet a beautiful woman who he later wed and
had you.
Your mother had a [Boy or Girl]: boy
And they named you: Name
You entered boy Name.
And they named you: Name
Are you sure you want to continue?
yes
This is the most important part of the intro
This decides your future stats and potentially future gameplay.
You have 20 points to put in any of the following category: Strength,
Health, Wisdom, or Dexterity.
Which attribute do you want to assign it to? strength
By how much? 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice: 3
name : Name
strength : 0
wisdom : 0
dexterity : 0
points : 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice:
Oh, and prompt for the name of the play goes again twice for some reason. Also, what does the my_character.keys() under def add_charater_points() mean? Since I just started to learn to code python, if there are any other tips you guys can give me it would be greatly appreciated.
The last two lines of this snippet
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
add the character points to the attribute, and immediately subtract them again. I think you might mean
my_character['points'] -= amount
Your repeated prompt is probably because you have a whole lot of code that logically seems to belong in function main() but is coded to run after main() finishes.

fill-in-the-blanks error in selecting other answer but the one given

This is my fill-in-the-blanks quiz I'm making. There's a problem when given the difficulty selection. At function def fill_in_the_blanks():
when the user type something other than the difficulty easy, medium, or hard it will end the game. I want it to go around the loop until the user picks the appropriate answer.
I want it to use def beginning_of_game(player_difficulty): too...
I'm not sure how to prevent it from ending the game when the user writes something else at the difficulty selection.
#easy-mode
driver_knowledge_test = ["When you're going to drive it is important to always put on your ___1___, including your passengers.",
"If there are no lanes marked on the road, you should drive in the ___2___ side of the road.",
"It's getting dark and the sun is fading, you should turn on the ___3___.",
"Before driving on a freeway, you should make sure you have enough ___4___, oil, water and the correct tyre pressure."]
answer_1 = ['seatbelts', 'left', 'light', 'fuel']
answered_list_1 = ["When you're going to drive it is important to always put on your seatbelts, including your passengers.",
"If there are no lanes marked on the road, you should drive in the left side of the road.",
"It's getting dark and the sun is fading, you should turn on the light. ",
"Before driving on a freeway, you should make sure you have enough fuel, oil, water and the correct tyre pressure."]
#medium-mode
general_food_test = ["All fruits have ___1___ in them. That's what makes them different from vegetables.",
"You shouldn't drink coffee or ___2___ when you're going to sleep. It keeps you up at night.",
"It is not safe to eat ___3___ undercooked. It might be contaminated with a bacteria called Salmonella.",
"The essentials to make a cake are flour, ___4___, vanilla extract, unsalted butter and egg."]
answer_2 = ['seeds', 'tea', 'chicken', 'sugar']
answered_list_2 = ["All fruits have seeds in them. That's what makes them different from vegetables.",
"You shouldn't drink coffee or tea when you're going to sleep. It keeps you up at night.",
"It is not safe to eat chicken undercooked. It might be contaminated with a bacteria called Salmonella.",
"The essentials to make a cake are flour, sugar, vanilla extract, unsalted butter and egg."]
#hard-mode
general_health_test = ["An ___1___ a day, keeps the doctor away.",
"Too much dietary intake of can be ___2___ for you. However, it is unlikely.",
"You can check your pulse on the wrist, ___3___, and thigh.",
"The averag amount of ___4___ adults need is 7-9 hours."]
anwser_3 = ['apple', 'harmful', 'neck', 'sleep']
answered_list_3 = ["An apple a day, keeps the doctor away.",
"Too much dietary intake of can be harmful for you. However, it is unlikely.",
"You can check your pulse on the wrist, neck, and thigh.",
"The averag amount of sleep adults need is 7-9 hours."]
blank_space = ["___1___", "___2___", "___3___", "___4___"]
#Inputs raw_input's name
#Outputs introduction with user's name
def Intro(name_of_player):
print "Hello " + name_of_player + ", we are going to play fill-in-the-blanks! Topics revolve around our everyday live, so don't worry if you didn't study much."
print "Please note the game is case-sensitive. i.e. all capslock must be disabled."
print "Let's get started, pick a difficulty."
#returns user's choice of list
def beginning_of_game(player_difficulty):
while True:
if player_difficulty == "easy":
print "You chose 'easy'\n"
return driver_knowledge_test, answer_1, answered_list_1 #use return function
elif player_difficulty == "medium":
print "You chose 'medium'\n"
return general_food_test, answer_2, answered_list_2
elif player_difficulty == "hard":
print "You chose 'hard'\n"
return general_health_test, answer_3, answered_list_3
else:
print "The following difficulty does not exist. Try again!"
#checks user input correct answer, and print out their progress. If user input incorrect, prompts to re-try
def answer_check(answer, sentence, blank_space, answered_list):
new_list = []
index = 0
sentence_index = 0
answer_index = 0
blank_index = 0
answered_list_index = 0
total_of_sentence = 4 #the number of elements in the sentence list.
print sentence[sentence_index]
while index < total_of_sentence:
print sentence[sentence_index]
player_answer = raw_input("\nType your answer for " + blank_space[blank_index] + " \n>>>")
if player_answer.lower() == answer[answer_index]:
#new_list.append(sentence[sentence_index])
new_list.append(answered_list[answered_list_index])
#current fill-in-the-blanks that's been already answered
print sentence[sentence_index].replace(blank_space[blank_index], answer[answer_index])
answered_list_index += 1
answer_index += 1
sentence_index += 1
index += 1
blank_index += 1
print "\nCCORRECT! \n"
else:
print "Wrong! Try again. :) \n"
print sentence
return "\nCongratulation! You completed the game!"
#inputs None
#Outputs whole program-functions
def fill_in_the_blanks():
name_of_player = raw_input("enter your name \n>>>")
Intro(name_of_player)
difficulty_selection = raw_input("\nselect from easy, medium, or hard \n>>>")
if difficulty_selection == "easy" or difficulty_selection == "medium" or difficulty_selection == "hard":
sentence, answers, answered_sentence = beginning_of_game(difficulty_selection)
print sentence
answer_check(answers, sentence, blank_space, answered_sentence)
print "\nThank you for playing!"
#initiate game from here.
fill_in_the_blanks()
A good old while loop:
def fill_in_the_blanks():
name_of_player = raw_input("enter your name \n>>>")
Intro(name_of_player)
difficulty_selection = ""
while difficulty_selection not in ["easy", "medium", "hard"]:
difficulty_selection = raw_input("\nselect from easy, medium, or hard \n>>>")
sentence, answers, answered_sentence = beginning_of_game(difficulty_selection)
print sentence
answer_check(answers, sentence, blank_space, answered_sentence)

Python: Making my adventure game code, begin to "do something."

absolute beginner here. I am making a text adventure game to sharpen beginner skills. Can someone give me an example of what could go in my
"def firstBattle", function?
Something like a small example of a battle, and updating the Stats and Inventory? Thanks
def displayIntro():
# I will update this as I think of more to add
print(""" You are lord Deadra. You have been sent to Citiel to
overthrow the current King Navator. Throughout your
travels, you will encounter various enemies of all
types. Good luck. """)
def displayInventory():
# Keeps a list of stuff in a dictionary. Because I returned
# stuff, I can use this function in other functions to update
print("Inventory:")
stuff = {"health potions": 5,
"poison": 5,
"stamina potions": 5,
"go crazy potion": 5,
"arrows": 50,
"hunting bow": 1,
"hunting knife": 1,
"big sword": 1,
"magic shield": 1}
return stuff
def displayStats():
# Displays initial health stats
print()
print("Stats:")
health = 100
stamina = 100
confidence = 100
return "health:",health, "stamina:",stamina, "confidence:",confidence
def firstBattle():
# First encounter with an enemy. After battle, update inventory
# and health stats
You need a damage variable.
Implement an enemyDamage, enemyHealth and yourDamage variable.
def battleScene():
print("ENTER to Attack.")
input()
health = health - enemyDamage
enemyHealth = enemyHealth - yourDamage
stamina = stamina - # What ever number you want stamina to go down
print("Your HP: " + health)
print("Enemy HP: " + enemyHealth)
To implement the weapons change their damage values using the a class block.

resetting raw_input within a while loop (python)

So I'm trying to get this engine to work, and I did, but it's broken my program. (from LPTHW)
I am basically trying to access a function where it gets an input from the user 11 times, if the user fails to guess the correct input, they die (in game) but my fix for sending the prompts from the engine to the functions, seemed to break the function where I get an input 11 times and just uses the same guess for all 11 inputs.
Here is the main engine
globvar = ' '
class Game(object):
def __init__(self, start):
self.quips = [
"You died. You kinda suck at this.",
"Your mom would be proud. If she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
self.start = start
def play(self):
# next_room_name is taken from init argument start
next_room_name = self.start
while True:
global globvar
print "\n--------"
# set variable room to get function from next_room_name
room = getattr(self, next_room_name)
print room.__doc__
if room == self.laser_weapon_armory:
prompt = raw_input("[keypad]> ")
elif room == self.escape_pod:
prompt = raw_input("[pod #]> ")
else:
prompt = raw_input("> ")
globvar = prompt
# unpacks function from next_room_name into room
next_room_name = room()
And here is the function im trying to get to work
def laser_weapon_armory(self):
"""
You do a dive roll into the Weapon Armory, crouch and scan the room
for more Gothons that might be hiding. It's dead quiet, too quiet.
You stand up and run to the far side of the room and find the
neutron bomb in its container. There's a keypad lock on the box
and you need the code to get the bomb out. If you get the code
wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits.
"""
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
guess = globvar
guesses = 0
while guess != code and guesses < 10:
print "BZZZZEDDD!"
guesses += 1
guess = globvar
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'
And here is the output I get
--------
You do a dive roll into the Weapon Armory, crouch and scan the room
for more Gothons that might be hiding. It's dead quiet, too quiet.
You stand up and run to the far side of the room and find the
neutron bomb in its container. There's a keypad lock on the box
and you need the code to get the bomb out. If you get the code
wrong 10 times then the lock closes forever and you can't
get the bomb. The code is 3 digits.
[keypad]> 124
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
BZZZZEDDD!
The lock buzzes one last time and then you hear a sickening
melting sound as the mechanism is fused together.
You decide to sit there, and finally the Gothons blow up the
ship from their ship and you die.
is this the kinda thing you're looking for? your question doesn't seem to be very clear
while guess != code and guesses < 10:
guess = raw_input("BZZZZEDDD! - try again?")
guesses += 1
guess = ''

Categories

Resources