Creating instances in a loop - python

I just started to learn about classes last week in my game dev. class. I am trying to create something that will allow me to create instances of something while in a for loop. For example, I am trying to create 5 instances of Player in a loop and use an ID number that will increase with each time the loop loops. I've gotten this far.
class Player(object):
def __init__(self, nm, am, wp, ht, ide):
self.name = nm
self.ammo = am
self.weapon = wp
self.health = ht
self.id = ide
def __str__(self):
values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
return values
def main():
Players = 0
while Players < 5:
play1 = Player("Joe", 5, "Machine gun", 22, 1)
print (play1)
Players = Players + 1
I've managed to create 5 instances of Joe which is fine, but how would I increase the ID #?

class Player(object):
def __init__(self, nm, am, wp, ht, ide):
self.name = nm
self.ammo = am
self.weapon = wp
self.health = ht
self.id = ide
def __str__(self):
values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
return values
def main():
Players = 0
while Players < 5:
play1 = Player("Joe", 5, "Machine gun", 22, Players)
print (play1)
Players = Players + 1
Use The Var Players And Put It Into The Class

I would put your players in an array so they can be used outside of the scope of the loop.
def main():
Players = 0
list_of_players = []
for i in range(5):
list_of_players.append(Player("Joe", 5, "Machine gun", 22, i+1))
print list_of_players[i]

You can use a list:
players = []
while len(players) < 5:
players.append(Player("Joe", 5, "Machine gun", 22, len(players) + 1))

Related

Python(3): TypeError: unsupported operand type(s) for -: 'str' and 'int'

so I am making a game that is basically just a Pokemon clone. It is very small compared to the actual game. I am making it for practice, and I keep on getting an error when trying to implement damage. It's on line 148-158. I don't know what is wrong, I've tried doing str() and int(), but those don't work. I know that firefox1 is supposed to have a number assigned to it, as well as waterblast, but It won't let me subtract them. I am very sorry if it's messy, I am new and just experimenting with code all the time. Thank you very much for taking your time to help me, If you need more info a will try to reply when I can.
#Python Project - Pokemon Clone - Game name: Pokymon
import time
import random
def health1():
health1 = random.randint(20,50)
return "This Pokymon is level 1, their health is " + str(health1)
one = health1()
def health2():
health2 = random.randint(50,80)
return "This Pokymon is level 2, their health is " + str(health2)
two = health2()
def health3():
health3 = random.randint(80,120)
return "This Pokymon is level 3, their health is " + str(health3)
three = health3()
def health4():
health4 = random.randint(120,160)
return "This Pokymon is level 4, their health is " + str(health4)
four = health4()
def health5():
health5 = random.randint(160,180)
return "This Pokymon is level 5, their health is " + str(health5)
five = health5()
def health6():
health6 = random.randint(180,220)
return "This Pokymon is level 6, their health is " + str(health6)
six = health6()
def health7():
health7 = random.randint(220,260)
return "This Pokymon is level 7, their health is " + str(health7)
seven = health7()
def health8():
health8 = random.randint(260,300)
return "This Pokymon is level 8, their health is " + str(health8)
eight = health8()
def health9():
health9 = random.randint(300,340)
return "This Pokymon is level 9, their health is " + str(health9)
nine = health9()
def health10():
health10 = random.randint(340,380)
return "This Pokymon is level 10, their health is " + str(health10)
ten = health10()
def boss():
boss = random.randint(450,620)
return "The boss's health is " + str(boss)
boss = boss()
def firefox1():
firefox1 = random.choice([one, two, three, four, five])
return "You encountered a firefox! " + str(firefox1)
def waterbat1():
waterbat1 = random.choice([one, two, three, four, five])
return "You encountered a waterbat! " + str(waterbat1)
def sandcat1():
sandcat1 = random.choice([one, two, three, four, five])
return "You encountered a sandcat! " + str(sandcat1)
def wagtail1():
wagtail1 = random.choice([one, two, three, four, five])
return "You encountered a wagtail! " + str(wagtail1)
def magmast1():
magmast1 = boss
return "You encountered the boss Magmast! You now have to fight him in order to go to the next island." + str(magmast1)
def waterfox():
waterfox = onehealth1
return "This is your new pokymon, " + str(waterfox)
def firefalcon():
firefalcon = onehealth1
return "This is your new pokymon, " + str(firefalcon)
def rockyram():
rockyram = onehealth1
return "This is your new pokymon, " + str(rockyram)
def windywallaby():
windywallaby = onehealth1
return "This is your new pokymon, " + str(windywallaby)
def onehealth1():
onehealth1 = random.randint(20,50)
return "Your Pokymon's level is 1, and your Pokymon's health is " + str(onehealth1)
def onehealth2():
onehealth2 = random.randint(50,80)
return "Your Pokymon's level is 2, and your Pokymon's health is " + str(onehealth2)
def onehealth3():
onehealth3 = random.randint(80,120)
return "Your Pokymon's level is 3, and your Pokymon's health is " + str(onehealth3)
def onehealth4():
onehealth4 = random.randint(120,160)
return "Your Pokymon's level is 4, and your Pokymon's health is " + str(onehealth4)
def onehealth5():
onehealth5 = random.randint(160,180)
return "Your Pokymon's level is 5, and your Pokymon's health is " + str(onehealth5)
def onehealth6():
onehealth6 = random.randint(180,220)
return "Your Pokymon's level is 6, and your Pokymon's health is " + str(onehealth6)
def onehealth7():
onehealth7 = random.randint(220,260)
return "Your Pokymon's level is 7, and your Pokymon's health is " + str(onehealth7)
def onehealth8():
onehealth8 = random.randint(260,300)
return "Your Pokymon's level is 8, and your Pokymon's health is " + str(onehealth8)
def onehealth9():
onehealth9 = random.randint(300,340)
return "Your Pokymon's level is 9, and your Pokymon's health is " + str(onehealth9)
def onehealth10():
onehealth10 = random.randint(340,380)
return "Your Pokymon's level is 10, and your Pokymon's health is " + str(onehealth10)
def waterblast():
waterblast = 20
return waterblast
def damage1(firefox1, waterblast):
damage1 = firefox1() - waterblast()
return "This pokymon now has " + str(damage1)
attack = input(firefox1() + " " + "Attack: ").lower().strip()
if attack == "Waterblast".casefold():
print(str(damage1(firefox1, waterblast)))
The problem is in the last line when you call dammage1(), you're passing a string with firefox1() and an int with waterblast()

need help figuring out why method updating_sitting and custmor_increment are not adding and printing out the way they should

class Restaurant():
"""intalizing attributes rest._type and food_type"""
def __init__(self,resturant_type,*food_type):
self.rest_type = resturant_type
self.food = food_type
self.number_severd = 0
def opening(self):
"""Letting people know that the resturant is open"""
print(self.rest_type.title() + " is now open")
def describing_rest(self):
"""telling you about resturant"""
print("\nWelcome to " + self.rest_type.title() +
" here are what we have on the menu today: ")
for self.foods in self.food:
print("-" + self.foods)
def updating_sitting(self,new_chart):
"""updating sitting chart"""
self.number_served = new_chart
def custmor_increment(self,addition):
"""add number to custmor count"""
self.number_severd += addition
rest = Restaurant('High Spot','Turkey sandwich','pizza','deserts')
rest.opening()
rest.describing_rest()
rest.number_severd = 230
print("we have " + str(rest.updating_sitting(400)))
print("now we have " + str(rest.custmor_increment(100)))
i need help figuring out how to method updating_sitting to print out how many are sitting now
and for custmor_increment to print what the new amount of custmors there is.
To print how many are sitting, the methods need to return self.number_served.
You also need to fix the typos number_severd and your indentation.
class Restaurant():
def __init__(self,resturant_type,*food_type):
"""intalizing attributes rest._type and food_type"""
self.rest_type = resturant_type
self.food = food_type
self.number_served = 0
def opening(self):
"""Letting people know that the resturant is open"""
print(self.rest_type.title() + " is now open")
def describing_rest(self):
"""telling you about resturant"""
print("\nWelcome to " + self.rest_type.title() +
" here are what we have on the menu today: ")
for self.foods in self.food:
print("-" + self.foods)
def updating_sitting(self,new_chart):
"""updating sitting chart"""
self.number_served = new_chart
return self.number_served
def custmor_increment(self,addition):
"""add number to custmor count"""
self.number_served += addition
return self.number_served
rest = Restaurant('High Spot','Turkey sandwich','pizza','deserts')
rest.opening()
rest.describing_rest()
rest.number_served = 230
print("we have " + str(rest.updating_sitting(400)))
print("now we have " + str(rest.custmor_increment(100)))
BTW, the correct spelling of "custmor" is "customer"

How Do I make the function "addlevels" work in my main code?

I am currently taking an online python class and am having issues with classes and methods. My teacher wants me to use the method "addlevels" to print out the original strength points + points in "addlevels" method.
I've tried to put return down in the method, but that did not work. I've also tried using Hero.strengthsPtsAdded and print(str(Hero.strengthPtsAdded)) but that also hasn't worked. When using str(Hero.strengthPts) it would only print out 90 instead of adding the 10 points.
class Superhero:
def __init__(self, name = "", strengthPts = 1):
self.name = name
self.strengthPts = strengthPts
def addlevels(self, points = 10):
strengthPtsAdded = self.strengthPts + points
def main():
Hero = Superhero("Falcon", 90,)
print("Name: " + Hero.name)
print("Level: " + str(Hero.strengthPts))
Hero.addlevels()
print("Heroes level after training " + str(Hero.strengthPts) + " .")
main()
I expected the code to output the name Falcon, the original strength points which would be 90, and then the strength points after adding which should be 100. The results though were that this code did print the name "Falcon" and the original strength points, but the last line printed "Heroes level after training: 90, instead of 100.
How about adding a new variable strengthPts_modified so to preserve the original strengthPts if yow want to use it later.
class Superhero:
def __init__(self, name = "", strengthPts = 1):
self.name = name
self.strengthPts = strengthPts
self.strengthPts_modified=self.strengthPts
def addlevels(self, points = 10):
self.strengthPts_modified += points
def main():
Hero = Superhero("Falcon", 90,)
print("Name: " + Hero.name)
print("Level: " + str(Hero.strengthPts))
Hero.addlevels()
Hero.addlevels()
print("Heroes level after training " + str(Hero.strengthPts_modified) + " .")
main()

I'm getting this error --> TypeError: string indices must be integers

I'm trying to learn object oriented programming by making a text based rpg which is shown below. The parts of it that are related to my question are:
def equipArmor(self):
for armor in self.armorsOwned:
select = 1
if self.armor == armor:
print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
else:
print(str(select) + ". " + str(armor["Name"]))
select += 1
armor_choice = input("Type the name of the armor you would like to equip\n")
for i in self.armorsOwned:
if armor_choice == i["Name"]:
if self.armor == i:
print("You already have that equipped")
else:
self.armor = i["Name"]
print("You equipped the {}".format(i["Name"]))
self.maxhp += i["Effect"]
and:
class Shop:
armors = {"BronzeArmor":{"Name": "Bronze armor",
"Cost": 30,
"Effect": 10},
"SilverArmor":{"Name": "Silver armor",
"Cost": 75,
"Effect": 20}}
Here is the rest just so you can understand the context of my code:
import time
import sys
class Player:
def __init__(self):
self.level = 1
self.exp = 0
self.gold = 0
self.maxhp = 20
self.hp = self.maxhp
self.attack = 1
self.weapon = ""
self.armor = ""
self.weaponsOwned = {}
self.armorsOwned = {}
def checkHp(self):
self.hp = max(0, min(self.hp, self.maxhp))
def deadCheck(self):
if self.hp == 0:
print("You died!")
sys.exit()
def equipArmor(self):
for armor in self.armorsOwned:
select = 1
if self.armor == armor:
print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
else:
print(str(select) + ". " + str(armor["Name"]))
select += 1
armor_choice = input("Type the name of the armor you would like to equip\n")
for i in self.armorsOwned:
if armor_choice == i["Name"]:
if self.armor == i:
print("You already have that equipped")
else:
self.armor = i["Name"]
print("You equipped the {}".format(i["Name"]))
self.maxhp += i["Effect"]
class Enemy:
def __init__(self, attack, maxhp, exp, gold):
self.exp = exp
self.gold = gold
self.maxhp = maxhp
self.hp = maxhp
self.attack = attack
def checkHp(self):
self.hp = max(0, min(self.hp, self.maxhp))
def enemyDeadCheck(self):
if self.hp == 0:
return True
class Shop:
armors = {"BronzeArmor":{"Name": "Bronze armor",
"Cost": 30,
"Effect": 10},
"SilverArmor":{"Name": "Silver armor",
"Cost": 75,
"Effect": 20}}
character = Player()
character.armorsOwned.update(Shop.armors["BronzeArmor"])
character.equipArmor()
What I'm trying to do is print out all of the armors I have, print "equipped" beside it if it's equipped, receive the name of the armor to equip from input, check if it is already equipped and then equip it if it isn't equipped. However, the error mentioned in the title is preventing me from doing that. Why is that so and what is a string indice?
Loops over dictionaries (for example, for i in self.armorsOwned) return an iterable of the keys, not the entries. So i is being set to the key string, not the armor dictionary.
You want to turn all your loops over dictionaries to something like:
for i in self.armorsOwned.values():
Dont have enough points to make comment hence posting as answer.
This error is generally thrown when you treat a list like a dictionary.
It'd be helpful if you could include the #line that shows the error so that I could pin-point but to me this looks fishy:
self.armorsOwned = {}
If it's just a dictionary of armor. In that case, this is how you would extract the armor-name:
if self.armor == armor:
print(str(select) + ". " + str(self.armorsOwned[armor]["Name"]) + " (Equipped)")
else:
print(str(select) + ". " + str(self.armorsOwned[armor]["Name"]))
You could also try printing the values of these variables to see what they contain before doing any string manipulation:
def equipArmor(self):
print(self.armorsOwned)
for armor in self.armorsOwned:
print(armor)
select = 1
TypeError: string indices must be integers is a very common error in Python, especially during development. It indicates that your variable is a string, but you are trying to use it as a dictionary.
example:
x = {'Name': 'Bronze Armor'}
print(x['Name']) # Bronze Armor
x = 'Bronze Armor'
print(x['Name']) # raises TypeError: string indices must be integers
Look at error's stack trace, it will tell you in which line you made the mistake.

Python 2.7.8: printing color/value with out the format

I'm new to python and about a month into learning. I came across an issue where when I run this code it's supposed to print out the numbers in red. The second example shows what it really prints out and I'm stuck. Please help.
It's supposed to print ('Enemy HP:', 1150/1200)
but it actually prints ('Enemy HP:', '\x1b[91m1150/1200\x1b[0m\n')
import random
class bcolors:
HEADER = '\033[95m'
OKBLUE = "\x1b[94m"
OKGREEN = "\x1b[92m"
WARNING = '\033[93m'
FAIL = '\x1b[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Person:
def __init__(self, hp, mp, atk, df, magic):
self.maxhp = hp
self.hp = hp
self.maxmp = mp
self.mp = mp
self.atkl = atk - 10
self.atkh = atk + 10
self.df = df
self.magic = magic
self.actions = ["Attack", "Magic"]
def generate_damage(self):
return random.randrange(self.atkl, self.atkh)
def generate_spell_damage(self, i):
mgl = self.magic[i]["dmg"] - 5
mgh = self.magic[i]["dmg"] + 5
return random.randrange(mgl, mgh)
def take_damage(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
def get_hp(self):
return self.hp
def get_max_hp(self):
return self.maxhp
def get_mp(self):
return self.mp
def get_max_mp(self):
return self.maxmp
def reduce_mp(self, cost):
self.mp -= cost
def get_spell_name(self, i):
return self.magic[i]["name"]
def get_spell_mp_cost(self, i):
return self.magic[i]["cost"]
def choose_action(self):
i = 1
print(bcolors.OKBLUE + bcolors.BOLD + "Actions" + bcolors.ENDC)
for item in self.actions:
print(str(i) + ":", item)
i += 1
def choose_magic(self):
i = 1
print(bcolors.OKBLUE + bcolors.BOLD + "Magic" + bcolors.ENDC)
for spell in self.magic:
print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
i = 1
from classes.game import Person, bcolors
magic = [{"name": "Fire", "cost": 10, "dmg": 100},
{"name": "Thunder", "cost": 10, "dmg": 124},
{"name": "Blizzard", "cost": 10, "dmg": 100}]
player = Person(460, 65, 60, 34, magic)
enemy = Person(1200, 65, 45, 25, magic)
running = True
i = 0
print(bcolors.FAIL + bcolors.BOLD + "AN ENEMY ATTACKS!" + bcolors.ENDC)
while running:
print("======================")
player.choose_action()
choice = input("Choose action:")
index = int(choice) - 1
if index == 0:
dmg = player.generate_damage()
enemy.take_damage(dmg)
print("You attacked for", dmg, "points of damage.")
elif index == 1:
player.choose_magic()
magic_choice = int(input("Choose magic:")) - 1
magic_dmg = player.generate_spell_damage(magic_choice)
spell = player.get_spell_name(magic_choice)
cost = player.get_spell_mp_cost(magic_choice)
current_mp = player.get_mp()
if cost > current_mp:
print(bcolors.FAIL + "\nNot enough MP\n" + bcolors.ENDC)
continue
player.reduce_mp(cost)
enemy.take_damage(magic_dmg)
print(bcolors.OKBLUE + "\n" + spell + " deals", str(magic_dmg), "points of damage" + bcolors.ENDC)
enemy_choice = 1
enemy_dmg = enemy.generate_damage()
player.take_damage(enemy_dmg)
print("Enemy attacks for", enemy_dmg)
print("----------------------------")
print("Enemy HP:", bcolors.FAIL + str(enemy.get_hp()) + "/" + str(enemy.get_max_hp()) + bcolors.ENDC + "\n")
print("Your HP:", bcolors.OKGREEN + str(player.get_hp()) + "/" + str(player.get_max_hp()) + bcolors.ENDC)
print("Your MP:", bcolors.OKBLUE + str(player.get_mp()) + "/" + str(player.get_max_mp()) + bcolors.ENDC + "\n")
if enemy.get_hp() == 0:
print(bcolors.OKGREEN + "You Win!", + bcolors.ENDC)
running = False
elif player.get_hp() == 0:
print(bcolors.FAIL + "Your enemy has defeated you!" + bcolors.ENDC)
running = False
Your code would work well in Python 3, where print is a function:
>>> print("x", "y")
x y
It means "print the first argument, then the separator (which defaults to a space), then the second argument.
In Python 2, though:
>>> print("x", "y")
('x', 'y')
prints a representation of the tuple containing your strings.
So, you can either use Python 3, which has many advantages, or change your code like this:
print("Enemy HP:" + bcolors.FAIL + str(enemy.get_hp()) + "/" +
str(enemy.get_max_hp()) + bcolors.ENDC + "\n")
# note the + instead of ,
in order to print a single string.
does it work for your others print ?
You have a double quote "" instead off simple '' on OKGREEN in class bcolors maybe it comes from here

Categories

Resources