I have been making a text-based game. I have gotten to a point where I am trying to do a battle. I have the enemy's hp going down but when I hit it again, the enemy's hp is back to what I had originally set it as. I hope these help.
while do != 'hit rat with sword' or 'run away':
enemyhp= 50
enemyattack= [0,1,3]
OldSwordattack= [0,1,4]
print('What do you do?(attack or run away)')
do=input()
if do == 'run away':
print('You can\'t leave mom like that!')
if do == 'hit rat with sword':
hit= random.choice(OldSwordattack)
if hit == OldSwordattack[0]:
print('Your swing missed')
print('Enemy\'s HP=' + str(enemyhp))
if hit == OldSwordattack[1]:
print('Your swing hit, but very lightly.')
enemyhp= enemyhp - 1
print('Enemy\'s HP=' + str(enemyhp))
if hit == OldSwordattack[2]:
print('Your swing hit head on!')
enemyhp= enemyhp - 4
print('Enemy\'s HP=' + str(enemyhp))
>In front of mom you see a giant, yellow-teethed rat.
>What do you do?(attack or run away)
>hit rat with sword
>Your swing hit, but very lightly.
>Enemy's HP=49
>What do you do?(attack or run away)
>hit rat with sword
>Your swing hit, but very lightly.
>Enemy's HP=49
>What do you do?(attack or run away)
You see? The above is the program running. I do not see why the value is not being changed.
because you are initializing it at the beginning of the iteration. So just move the
enemyhp= 50
before the while loop, like this
enemyhp= 50
while do != 'hit rat with sword' or 'run away':
Just for fun I've extended your example program to include some more advanced language constructs. May you find it entertaining: (Python 3)
import random
import re
def dice(s, reg=re.compile('(\d+d\d+|\+|\-|\d+)')):
"""
Executes D+D-style dice rolls, ie '2d6 + 3'
"""
total = 0
sign = 1
for symbol in reg.findall(s):
if symbol == '+':
sign = 1
elif symbol == '-':
sign = -1
elif 'd' in symbol:
d,s = [int(k) for k in symbol.split('d')]
for i in range(d):
total += sign * random.randint(1, s)
else:
total += sign * int(symbol)
return total
class Character():
def __init__(self, name, attack, defense, health, weapon):
self.name = name
self.attack = attack
self.defense = defense
self.health = health
self.weapon = weapon
def hit(self, target):
if self.is_dead:
print('{} is trying to become a zombie!'.format(self.name))
return 0
attack = self.attack + self.weapon.attack_bonus + dice('2d6')
defense = target.defense + dice('2d6')
if attack > defense:
damage = int(random.random() * min(attack - defense + 1, self.weapon.damage + 1))
target.health -= damage
print('{} does {} damage to {} with {}'.format(self.name, damage, target.name, self.weapon.name))
return damage
else:
print('{} misses {}'.format(self.name, target.name))
return 0
#property
def is_dead(self):
return self.health <= 0
class Weapon():
def __init__(self, name, attack_bonus, damage):
self.name = name
self.attack_bonus = attack_bonus
self.damage = damage
def main():
name = input("So, what's your name? ")
me = Character(name, 4, 6, 60, Weapon('Old Sword', 2, 4))
mom = Character('Mom', 2, 2, 50, Weapon('Broom', 0, 1))
rat = Character('Crazed Rat', 5, 2, 40, Weapon('Teeth', 1, 2))
print("You are helping your mother clean the basement when a Crazed Rat attacks. "
"You grab your Grandfather's sword from the wall and leap to defend her!")
actors = {me, mom, rat}
coward = False
killer = None
while (me in actors or mom in actors) and rat in actors:
x = random.choice(list(actors))
if x is mom:
mom.hit(rat)
if rat.is_dead:
killer = mom
actors -= {rat}
elif x is rat:
target = random.choice(list(actors - {rat}))
rat.hit(target)
if target.is_dead:
actors -= {target}
if target is mom:
print('Your mother crumples to the floor. AARGH! This rat must die!')
me.attack += 2
else:
print('Well... this is awkward. Looks like Mom will have to finish the job alone...')
else: # your turn!
print('Me: {}, Mom: {}, Rat: {}'.format(me.health, 0 if mom.is_dead else mom.health, rat.health))
do = input('What will you do? [hit] the rat, [run] away, or [swap] weapons with Mom? ')
if do == 'hit':
me.hit(rat)
if rat.is_dead:
killer = me
actors -= {rat}
elif do == 'run':
if me.health < 20:
actors -= {me}
coward = True
else:
print("Don't be such a baby! Get that rat!")
elif do == 'swap':
me.weapon, mom.weapon = mom.weapon, me.weapon
print('You are now armed with the {}'.format(me.weapon.name))
else:
print('Stop wasting time!')
if rat.is_dead:
if mom.is_dead:
print('The rat is gone - but at a terrible cost.')
elif me.is_dead:
print("Your mother buries you with your trusty sword by your side and the rat at your feet.")
elif coward:
print("The rat is gone - but you'd better keep running!")
elif killer is me:
print("Hurrah! Your mother is very impressed, and treats you to a nice cup of tea.")
else:
print('Your mother kills the rat! Treat her to a nice cup of tea before finishing the basement.')
else:
print('I, for one, hail our new rat overlords.')
if __name__=="__main__":
main()
Related
import random
class Tamagotchi:
def __init__(self, name, animaltype, activities):
self.name = name
self.animaltype = animaltype
self.activities = activities
self.energy = 100
def getName(self):
return self.name
def getAnimalType(self):
return self.animaltype
def getEnergy(self):
return self.energy
def setHealth(self, newHealth):
self.energy = newHealth
def getExercise():
activity = random.choice(activities)
return (activity)
class Donkey (Tamagotchi):
def __init__ (self, name, activities):
super().__init__(name, "Donkey", activities)
self.__home = "Beach"
def getHome(self):
return (self.__home)
def __fightingSkill(self):
print(self.name, "fights by kicking with their back leg straight into the opponents head")
def DoExercise(self, activity):
if activity == "fighting":
energy = round(self.energy - 10)
print(energy)
print("Strong Kick")
if activity == "racing":
energy = round(self.energy - 15)
print("Hard work")
if activity == "Tail Launch":
energy = round(self.energy - 1)
print("I am a donkey, not a Walrus")
self.setHealth(energy)
if self.getEnergy() < 70:
print(self.getName(), "Is out of energy")
else:
print(self.getName(), "Tired, New Energy:", self.getEnergy())
class Horse(Tamagotchi):
def __init__(self, name, activities):
super().__init__(name, "Horse", activities)
def DoExercise(self, activity):
if activity == "fighting":
energy = round(self.energy - 15)
print("Beaten")
if activity == "racing":
energy = round(self.energy - 5)
print("I am a racing horse")
if activity == "Tail Launch":
energy = round(self.energy - 2)
print("I am a horse i dont tail launch")
self.setHealth(energy)
if self.getEnergy() < 70:
print(self.getName(), "Is out of energy")
else:
print(self.getName(), "Tired, New Energy:", self.getEnergy())
class Walrus(Tamagotchi):
def __init__(self, name, activities):
super().__init__(name, "Walrus", activities)
def DoExercise(self, activity):
if activity == "fighting":
energy = round(self.energy - 34)
print("Victorious")
if activity == "racing":
energy = round(self.energy - 5)
print("I am a Walrus, i dont race")
if activity == "Tail Launch":
energy = round(self.energy - 12)
print("Get launched lol")
self.setHealth(energy)
if self.getEnergy() < 70:
print(self.getName(), "Is out of energy")
else:
print(self.getName(), "Tired, New Energy:", self.getEnergy())
Pet1 = Donkey("Gracy", "fighting")
print("Player1, you are", Pet1.getName(), "who is a", Pet1.getAnimalType())
Pet2 = Horse("Mabel", "racing")
print("Player2, you are", Pet2.getName(), "who is a", Pet2.getAnimalType())
Pet3 = Walrus("Steve", "Tail Lauch")
print("Player3, you are", Pet3.getName(), "who is a", Pet3.getAnimalType())
activities = []
activities.append(Pet1.activities)
activities.append(Pet2.activities)
activities.append(Pet3.activities)
print(activities)
activity = Tamagotchi.getExercise()
print("Activity chosen", activity)
#Accessing private attributes
Pet1.__home = "Land"
print(Pet1.name, "lives on a", Pet1.getHome())
#Accessing private methods
Pet1._Donkey__fightingSkill()
while Pet1.getEnergy()>70 and Pet2.getEnergy()>70 and Pet3.getEnergy() > 70:
Pet1.DoExercise(activity)
if Pet2.getEnergy() > 70:
Pet2.DoExercise(activity)
if Pet3.getEnergy() > 70:
Pet3.DoExercise(activity)
if Pet1.getEnergy() >Pet2.getEnergy()and Pet3.getEnergy():
print("Player 1 wins")
else:
if Pet3.getEnergy() > Pet2.getEnergy():
print("Player 3 wins")
else:
print("Player 2 wins")
this code doesn't seem to work, any suggestions?
pls can you make the code work, im not the best at pyhton but i give it my all, any help would be greatly appreciated
Ive been working at it for 2 days now and it doesnt seem to work, it talks about an error which is:
'local variable 'energy' referenced before assignment'
and another error presented is;
'line 126, in
Pet1.DoExercise(activity)'
Mercinator
The error essentially means you are asking to use the value of "energy" even though it is empty(None/null)
In def DoExercise(self, activity): add an else statement that defines the value of energy when all if cases fail or give the value of energy before the if statement begins. It should solve the issue.
I'm trying to use a new enemy every time the hero levels up. The code itself works without a problem. The player levels, up, he uses magic and mana, the enemy hits back, and all that jazz. I just can't figure out a way to throw in a new enemy every time the player kills the enemy. Any ideas?
class Character:
def __init__(self, name, health, level):
self.name = name
self.health = health
self.level = level
self.levelup_counter = level + 1
def attack(self):
c2.health -= 2
c1 = Character("Hero", 10, 1)
c2 = Character("Monster 1", 10, 2)
c3 = Character("Monster 2", 20, 3)
c4 = Character("Monster 3", 40, 4)
# monster_list = [c2,c3,c4]
def stats():
print("_______________________________________")
print("Your stats \t\tEnemy Stats")
print("---------------------------------------")
print(f"Health: {c1.health}\t\tHealth: {c2.health}")
print(f"Level: {c1.level}\t\tLevel: {c2.level}")
while True:
attack = input("Enter 1 to attack: ")
c1.attack()
stats()
if c2.health == 0:
c1.level += 1
print("YOu killed the monster!\nYou leveled up!")
continue
UPDATE:
UPDATE:
I made a few changes and added a for loop to iterate over the monster list. Now I have two problems. First, the monsters keep iterating (obviously) instead of simply one monster fighting until death. Then, a new monster will appear. Second, I can't remove a monster from the list after death. I get the error "TypeError: 'Character' object cannot be interpreted as an integer"
class Character:
def __init__(self, name, health, level):
self.name = name
self.health = health
self.level = level
self.levelup_counter = level + 1
def attack(self):
m.health -= 2
def monster_death(self):
if m.health == 0:
monster_list.pop(m)
c1 = Character("Hero", 10, 1)
c2 = Character("Monster 1", 10, 2)
c3 = Character("Monster 2", 20, 3)
c4 = Character("Monster 3", 40, 4)
monster_list = [c2,c3,c4]
def stats():
print("_______________________________________")
print("Your stats \t\tEnemy Stats")
print("---------------------------------------")
print(f"Health: {c1.health}\t\tHealth: {m.health}")
print(f"Level: {c1.level}\t\tLevel: {m.level}")
i=0
while True:
i+=1
for m in monster_list:
attack = input("Enter 1 to attack: ")
c1.attack()
stats()
if m.health == 0:
c1.level += 1
print("YOu killed the monster!\nYou leveled up!")
m.monster_death()
continue
To fix the first issue, just add a while loop for each monster that continues until the health is less than or equal to 0. I have shown this in the code below. Also your "i" counter was completely unused from what I could tell.
while True:
for m in monster_list:
while m.health > 0:
attack = input("Enter 1 to attack: ")
c1.attack()
stats()
if m.health <= 0:
c1.level += 1
print("YOu killed the monster!\nYou leveled up!")
m.monster_death()
As for the second issue with removing the monsters from the list, I think that is a bad idea while you are iterating through a for loop. By removing the monsters from the list while looping through them, you are going to get indexing errors and it will skip monster number 3. If you want to get rid of the error you are getting though, simply change this line: monster_list.pop(m) to monster_list.remove(m).
What #furas said above is a good suggestion. You could do something like this (pseudocode but you get the idea):
while len(monster_list) > 0:
while monster_list[0].health > 0:
# attack
if monster_list[0].health <= 0:
# kill monster and remove monster_list[0]
You could keep monsters on list and fight always with first monster on list - monster_list[0]. And when you kill it then remove() it - and then you can append new monster at the end of list.
Minimal working code
# --- classes ---
class Character:
def __init__(self, name, health, level):
self.name = name
self.health = health
self.level = level
self.levelup_counter = level + 1
def attack(self):
self.health -= 2
def monster_death(self):
if self.health <= 0: # better check `<=` instead of `==`
monsters.remove(self)
def __str__(self):
return f'name: {self.name}, health: {self.health}, level: {self.level}'
# --- functions ---
def stats(player, monster):
print("_______________________________________")
print("Your stats \t\tEnemy Stats")
print("---------------------------------------")
print(f"Health: {player.health}\t\tHealth: {monster.health}")
print(f"Level: {player.level}\t\tLevel: {monster.level}")
# --- main ---
player = Character("Hero", 10, 1)
monsters = [
Character("Monster 1", 10, 2),
Character("Monster 2", 20, 3),
Character("Monster 3", 40, 4),
]
#monsters = []
#for i in range(1, 4):
# monsters.append( Character(f"Monster {i}", i*10, i+1),
i = 3 # used for monster's name
while monsters:
m = monsters[0]
print('New monster attacked:', m) # it will use `__str__` to display `m`
while True:
attack = input("Enter 1 to attack: ")
m.attack()
stats(player, m)
if m.health <= 0: # better check `<=` instead of `==`
player.level += 1
print("You killed the monster!\nYou leveled up!")
m.monster_death()
i += 1
monsters.append( Character(f"Monster {i}", i*10, i+1) )
break # exit nearest `while`
I have problems implementing the base power code on my Pokemon battle game on Python. Thanks if you wanna help.
Here's my code:
import time
import numpy as np
import sys
# Delay printing
def delay_print(s):
# print one character at a time
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
# Create the class
class Pokemon:
def __init__(self, name, types, moves, EVs, health='==================='):
# save variables as attributes
self.name = name
self.types = types
self.moves = moves
self.attack = EVs['ATTACK']
self.defense = EVs['DEFENSE']
self.health = health
self.bars = 20 # Amount of health bars
def fight(self, Pokemon2):
print("POKEMON BATTLE WOOOOOOOOOOOO!!!!!!")
print(f"\n{self.name}")
print("TYPE/", self.types)
print("ATTACK/", self.attack)
print("DEFENSE/", self.defense)
print("LVL/", 3 * (1 + np.mean([self.attack, self.defense])))
print("\nVS")
print(f"\n{Pokemon2.name}")
print("TYPE/", Pokemon2.types)
print("ATTACK/", Pokemon2.attack)
print("DEFENSE/", Pokemon2.defense)
print("LVL/", 3 * (1 + np.mean([Pokemon2.attack, Pokemon2.defense])))
time.sleep(2)
# Consider type advantages
version = ['Fire', 'Water', 'Grass']
for i, k in enumerate(version):
if self.types == k:
# Both are same type
if Pokemon2.types == k:
string_1_attack = '\nIts not very effective...'
string_2_attack = '\nIts not very effective...'
# Pokemon2 is STRONG
if Pokemon2.types == version[(i + 1) % 3]:
Pokemon2.attack *= 2
Pokemon2.defense *= 2
self.attack /= 2
self.defense /= 2
string_1_attack = '\nIts not very effective...'
string_2_attack = '\nIts super effective!'
# Pokemon2 is WEAK
if Pokemon2.types == version[(i + 2) % 3]:
self.attack *= 2
self.defense *= 2
Pokemon2.attack /= 2
Pokemon2.defense /= 2
string_1_attack = '\nIts super effective!'
string_2_attack = '\nIts not very effective...'
# Now for the actual fighting...
# Continue while pokemon still have health
while (self.bars > 0) and (Pokemon2.bars > 0):
# Print the health of each pokemon
print(f"\n{self.name}\t\tHLTH\t{self.health}")
print(f"{Pokemon2.name}\t\tHLTH\t{Pokemon2.health}\n")
print(f"{self.name}, I choose you!")
for i, x in enumerate(self.moves):
print(f"{i + 1}.", x)
index = int(input('Pick a move: '))
delay_print(f"\n{self.name} used {self.moves[index - 1]}!")
time.sleep(1)
delay_print(string_1_attack)
# Determine damage
Pokemon2.bars -= self.attack
Pokemon2.health = ""
# Add back bars plus defense boost
for j in range(int(Pokemon2.bars + .1 * Pokemon2.defense)):
Pokemon2.health += "="
time.sleep(1)
print(f"\n{self.name}\t\tHLTH\t{self.health}")
print(f"{Pokemon2.name}\t\tHLTH\t{Pokemon2.health}\n")
time.sleep(.5)
# Check to see if Pokemon fainted
if Pokemon2.bars <= 0:
delay_print("\n..." + Pokemon2.name + ' fainted. ' +
self.name + " won!")
break
# Pokemon2s turn
print(f"Let's go, {Pokemon2.name}!")
for i, x in enumerate(Pokemon2.moves):
print(f"{i + 1}.", x)
index = int(input('Pick a move: '))
delay_print(f"\n{Pokemon2.name} used {Pokemon2.moves[index - 1]}!")
time.sleep(1)
delay_print(string_2_attack)
# Determine damage
self.bars -= Pokemon2.attack
self.health = ""
# Add back bars plus defense boost
for j in range(int(self.bars + .1 * self.defense)):
self.health += "="
time.sleep(1)
print(f"{self.name}\t\tHLTH\t{self.health}")
print(f"{Pokemon2.name}\t\tHLTH\t{Pokemon2.health}\n")
time.sleep(.5)
# Check to see if Pokemon fainted;;
if self.bars <= 0:
delay_print("\n..." + self.name + ' fainted. ' +
Pokemon2.name + " won!")
break
class moves:
self.firemoves = ["Eruption", "Fire Blast", "Flamethrower", "Overheat"]
self.watermoves = ["Razor Shell", "Scald", "Hydro Pump", "Surf"]
self.grassmoves = ["Leaf Storm", "Energy Ball", "Giga Drain", "Solar Beam"]
def BasePower():
BasePower =
def Damage():
damage = ((2 * Level + 2) * Power * ATTACK / DEFENSE / 50 + 2)
money = np.random.choice(5000)
delay_print(f"\nOpponent paid you ${money}. Good luck in the future and win more batttles!\n")
if __name__ == '__main__':
# Create Pokemon
Typhlosion = Pokemon(
'Typhlosion', 'Fire',
['Eruption: 150 Base Power, power decreases as health decreases',
'Fire Blast: 110 Base Power, 10% chance to burn', 'FLamethrower: 90 Base Power, 10% chance to burn',
'Overheat, 130 Base Power, lowers attack by 2'], {
'ATTACK': 12,
'DEFENSE': 8
})
Samurott = Pokemon('Samurott', 'Water',
['Razor Shell: 75 Base Power', 'Scald: 80 Base Power', 'Hydro Pump: 120 Base Power',
'Surf: 90 Base Power'], {'ATTACK': 10, 'DEFENSE': 10
})
Serperior = Pokemon(
'Serperior', 'Grass',
['Leaf Storm: 130 Base Power, lowers attack by 2', 'Energy Ball: 90 Base Power',
'Giga Drain: 75 Base Power, yo heal 50% of damage dealt',
'Solar Beam: 120 Base Power, takes two turns to charge'], {
'ATTACK': 19,
'DEFENSE': 1
})
Typhlosion.fight(Samurott) # Get them to fight'
So as you can see here, the moves such as Typhlosion's Eruption or Serperior's Leaf Storm doesn't have their base power, as Eruption supposedly have 150 base power in full health, and Leaf Storm should have 130 base power, while dropping your attack by two.
The title is terrible, but hopefully I can explain in my post. Creating a little game as my pet project for python, and I'm currently creating the inventory. Everything was... ok when developing the game until it came to making the function that will show all of the player's inventory.
elif (prompt == "examine"):
print(inventory[1].name)
gameprompt()
Ok, so I created a list that basically has a bunch of classes from Items in it. To call on the name element of these classes I have to do something like this, otherwise I just get its memory location which is largely useless to the player. I've tried
elif (prompt == "examine"):
print(inventory[].name)
gameprompt()
Thought that this above example would print only the name of all the Item objects, but there's a compilation error instead because I didn't specify which one. So I then tried~
elif (prompt == "examine"):
print(inventory[1:1000].name)
gameprompt()
Thinking that it would print all of the Item objects names up to 1000, but I obviously don't have that so I thought it would print the names up to the latest object that was there and stop but there was another compilation error from this...
If there is anyway to print out an element of a class for all class objects in a list please let me know. The full code of this game is here, although I don't think you'll need it to help me solve my problem (it is also very large.)
playername = input("What is your name?")
zone = 1
movement = 0
restcounter = 0
searchcounter = 0
class Player:
def __init__(self, name, hp, mp, atk, xp, dodgerate, atkrate):
self.name = playername
self.hp = hp
self.mp = mp
self.atk = atk
self.xp = xp
self.dodgerate = dodgerate
self.atkrate = atkrate
class Enemy(Player):
def __init__(self, name, gold, maxhp, hp, mp, atk, xp):
self.name = name
self.gold = gold
self.maxhp = maxhp
self.hp = hp
self.mp = mp
self.atk = atk
self.xp = xp
class Items:
def __init__(self, name, quantity, description, price, weight):
self.name = name
self.quantity = quantity
self.description = description
self.price = price
self.weight = weight
Player = Player(playername, 1, 1, 1, 1, 25, 3)
print(Player.name + " has been created. ")
def raceselection():
raceinput = input("Do you float towards the TEMPLE, CAVE or FOREST?")
if raceinput == "TEMPLE":
print("You are now a high elf. High elves utlize a lot of magical power at the cost of being very frail.")
Player.hp = Player.hp + 24
Player.mp = Player.mp + 100
Player.atk = Player.atk + 50
print("You awaken from your slumber. Your room's walls are gold plated, and you rested on a flat board.")
print("Out the door, you see many elves with robes praying to some goddess.")
print("You walk out of your door and into the praying area. You are immediately greeted by a tall man.")
elif raceinput == "CAVE":
print("You are now an orc.")
Player.hp = Player.hp + 1000
Player.mp = Player.mp + 15
Player.atk = Player.atk + 50
print("cave")
elif raceinput == "FOREST":
print("You are now a human.")
Player.hp = Player.hp + 50
Player.mp = Player.mp + 25
Player.atk = Player.atk + 25
else:
print("You can't float there!")
raceselection()
raceselection()
inventory = []
def gameprompt():
global inventory
global zone
global movement
global restcounter
global searchcounter
if (movement == 5):
movement = movement - movement
zone = zone + 1
print("You have advanced to zone",zone,"!!!")
gameprompt()
if (zone == 1):
print("Welcome to the first zone! Easy enemies are here with not very good loot./fix grammar, add description of zone/")
elif (zone == 2):
print("Hey, it actually travelled to the second zone, awesome!")
elif (zone == 3):
print("No way would this actually work!")
prompt = input("Would you like to walk, search or rest?: ")
if (prompt == "walk"):
encounterchance = random.randint(1, 3)
if (encounterchance == 2):
if (zone == 1):
mobspawnrate = random.randint(1,3)
if (mobspawnrate == 1):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
elif (mobspawnrate == 2):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
elif (mobspawnrate == 3):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
else:
movement = movement + 1
print("You have walked a step. You are now at ",movement," steps")
gameprompt()
elif (prompt == "search"):
if (searchcounter == 3):
print("You cannot search this area anymore! Wait until you reach the next zone!")
gameprompt()
else:
searchchance = random.randint(1, 5)
if (searchchance == 1 or 2 or 3 or 4):
searchcounter = searchcounter + 1
print(searchcounter)
print("You have found something!")
searchchance = random.randint(1,4)
if (searchchance == 1 or 2):
inventory.append(Items("Old Boot", 1, "An old smelly boot. It's a mystery as to who it belongs to...", 5, 50))
print("You have found a Boot!")
print(inventory)
elif(searchchance == 3):
inventory.append(Items("Shiny Boot", 1, "Looks like a boot that was lightly worn. You could still wear this.", 5, 50))
print(inventory)
print("You have found a Shiny Boot!")
elif(searchchance == 4):
inventory.append(Items("Golden Boot", 1, "It's too heavy to wear, but it looks like it could sell for a fortune!", 5, 50))
print("You have found a Golden Boot?")
print(inventory)
else:
searchcounter = searchcounter + 1
print(searchcounter)
print("You did not find anything of value")
gameprompt()
elif (prompt == "rest"):
if (restcounter == 1):
print("Wait until you reach the next zone to rest again!")
gameprompt()
else:
# Add a MaxHP value to the player later, and the command rest will give 25% of that HP back.
Player.hp = Player.hp + (Player.hp / 5)
print("You have restored ",(Player.hp / 5)," hit points!")
restcounter = restcounter + 1
gameprompt()
elif (prompt == "examine"):
print(inventory[1].name)
gameprompt()
gameprompt()
A list comprehension or map would work perfectly here:
print([item.name for item in inventory])
The comprehension iterates the list, and "replaces" each element in the list with whatever the part before for evaluates to. In this case, it's item.name.
° It actually doesn't replace the element in the original list. It evaluates to a new list full of replaced items.
In my previous post I stated that my variable would not change whenever I added something to it. Here is my current code and my problem will be below it.
#creates random monsters with xp points, leveling up player, and adding upgrades
#imports
from clint.textui import colored, puts
import random
sticks = 2
stumps = 2
stone = 0
iron_in = 0
gold_in = 0
diamond = 0
platinum = 0
w_sword = 1
w_shield = 1
items = ('sticks:' + str(sticks) + ' stumps:' + str(stumps) + ' stone:' + str(stone) + ' iron ingot:' + str(iron_in) + ' gold ingot:' + str(gold_in) + ' diamond:' + str(diamond) + ' platinum:' + str(platinum) + ' Wooden sword(s):' + str(w_sword) +
' wooden shield(s):' + str(w_shield))
def game():
#start of the game
def start_game():
print(' Hello player! Welome to a text based game involving killing monsters, leveling up, crafting weapons, and upgrading weapons!!!')
print(' To get started enter in (i)inventory (c)craft items (d)description of items (m)types of monsters or (f)fight monsters.')
print(' ENTER (help) FOR HOW THE GAME WORKS')
print(' ENTER(?) FOR TO PRINT THIS AGAIN')
print(' WHILE YOU ARE IN A CATEGORY SUCH AS (i)inventory PRESS (?) CAN BE USED TO GO BACK AND GO TO ANOTHER CATEGORY')
start_game()
main_In = input()
level = 0
Pxp = 0
gold = 5
monster_lvl = random.randint(1,10)
if main_In == ('c'):
ws_sticks = 2
ws_stumps = 1
def craft():
print('Would you like to craft an item??')
print('( Red = uncraftable )')
print('( Green = craftable )')
print('( Type items in lowercase )')
if sticks < ws_sticks:
puts(colored.red('Wooden sword'))
else:
puts(colored.green('Wooden sword'))
if stumps < ws_stumps:
puts(colored.red('Wooden shield'))
else:
puts(colored.green('Wooden shield'))
craft()
C_item = input()
def re_craft():
print('press ENTER to go back to the start screen, or enter c to craft an(other) item.')
cor_go = input()
if cor_go == ('c'):
craft()
C_item = input()
else:
game()
if C_item == ('no'):
print('press ENTER to go back to the start screen')
input()
game()
if C_item == ('wooden sword') and sticks >= ws_sticks:
print('Wooden sword added to your inventory')
re_craft()
if C_item == ('wooden sword') and sticks < ws_sticks:
print('You need ' + str(ws_sticks - sticks) + ' stick(s) to craft a wooden sword')
re_craft()
if C_item == ('wooden shield') and stumps >= ws_stumps:
print('Wooden shield added to your inventory')
re_craft()
if C_item == ('wooden shield') and stumps < ws_stumps:
print('You need' + str(ws_stump - stumps) + ' stumps to craft a wooden shield.')
re_craft()
while ('Wooden shield added to your inventory'):
w_shield += 1
while ('Wooden sword added to your inventory'):
w_sword = +1
if main_In == ('i'):
puts(colored.yellow('Level: ' + str(level)))
puts(colored.yellow('xp: ' + str(Pxp)))
puts(colored.yellow('gold:' + str(gold)))
puts(colored.yellow('Items: ' + str(items)))
puts(colored.yellow('press ENTER to return to the start screen'))
input()
game()
if main_In == ('?'):
game()
game()
Now one of the answers in my last question said that my variable for w_sword and w_shield should start as 1 and that my variable assignments should be outside the function: game(), so I did as said and whenever I "crafted" a wooden sword or wooden shield it showed up as 1 for it. But what I didn't realize was that no matter which I crafted (wooden sword or wooden shield) both w_sword and w_shield showed up as 1 when I went back to (i)inventory. For instance
If I was to type wooden sword in the input known as c_item and then go back to (i)inventory, both w_sword and w_shield would show up as 1 even though I only crafted a wooden sword.