Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iterating Variables...?
#1
I am brand new to coding (it has been about 48 hours since I decided to give it a go), so I'm sure the answer to this problem is something simple, however I don't know enough of the jargon yet to even successfully search it out on google. Thank you ahead of time for any help you can provide.

I am using the Pycharm IDE and the Python language.

I have written code which randomly generates attributes for an object, once the data is generated, it gets assigned to the class: soldier01 = Soldier(data....). At the end of the function, you have the option of generating a new set of data (rolling a new soldier) which just re-runs the same code.

All of that is working fine, the thing I can't figure out is how to iterate the name of the object for successive instances. I would like the instance to be "soldier02" the second time I run the function, then "soldier03," etc.

I can provide the code if that will help, but the code is all working as expected (no errors). I just don't know how to do this thing.

Thanks again for your input.
Reply
#2
Please show code
Reply
#3
(May-15-2019, 05:58 AM)JesseTheNewb Wrote: I would like the instance to be "soldier02" the second time I run the function, then "soldier03," etc.
No, you don't want to go this way. It's anti pattern. You should create multiple instances (soldiers) and store each of these instances in a data structure like list.

very basic example

import random

class Soldier:
    def __init__(self, strength):
        self.strength = strength
    
    def __str__(self):
        return (f'Soldier with strength {self.strength}')

my_army = []
for soldier in range(10):
    my_army.append(Soldier(strength=random.randint(5, 10)))

# print all soldiers in the army    
for soldier in my_army:
    print(soldier)

print()
print(my_army[3]) # print again 4th Soldier
Output:
Soldier with strength 8 Soldier with strength 7 Soldier with strength 5 Soldier with strength 6 Soldier with strength 5 Soldier with strength 10 Soldier with strength 10 Soldier with strength 8 Soldier with strength 5 Soldier with strength 9 Soldier with strength 6 >>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Ok, i'm not sure how much of the code to include... I'll throw it all in, I guess.

import random

names_first = ["Joe", "Jim", "Jeff"]
names_sir = ["Johnson", "Jansen", "Jetson"]
knighted_members = []
citizen_names = []
promotion = "Yes"


class Knight:
    def __init__(self, name, statbp, statbs, statbb):
        self.name = name
        self.statbp = statbp
        self.statbs = statbs
        self.statbb = statbb


def population_generation():

    """This function asks user for a number then generates that many
     random names and stores those names in a list then prints the list."""

    population = input("How many citizens occupy your stronghold? ")

    print("\nYou have " + population + " citizens, here are their names:\n")

    pop = int(population)

    while pop > 0:
        first = random.choice(names_first)
        sir = random.choice(names_sir)
        # print(first + " " + sir)
        citizen_names.append(first + " " + sir)
        pop = pop - 1


def knight_stat_gen():

    """This function creates three lists. The first list consists
    of randomly generated numbers called 'primary stats'. The
    second and third lists are derivatives of the first."""
    knight_counter = 0

    stat_block_prime = [5, 5, 5, 5, 5, 5, 5]

    prime_counter = 0

    while prime_counter < 7:
        roll = random.normalvariate(55, 15)
        stat = round(roll)
        if 9 < stat < 101:
            stat_block_prime[prime_counter] = stat
            prime_counter += 1

    # print(stat_block_prime)

    Agility = stat_block_prime[0]
    Charisma = stat_block_prime[1]
    Cunning = stat_block_prime[2]
    Endurance = stat_block_prime[3]
    Loyalty = stat_block_prime[4]
    Spirit = stat_block_prime[5]
    Strength = stat_block_prime[6]

    print("\nPrimary Stats\n")
    print("Agility: ", Agility)
    print("Charisma: ", Charisma)
    print("Cunning: ", Cunning)
    print("Endurance: ", Endurance)
    print("Loyalty: ", Loyalty)
    print("Spirit: ", Spirit)
    print("Strength: ", Strength)
    print("")
    print("")

    # secondary stats

    bcheck = 0

    while bcheck == 0:
        roll = random.normalvariate(55, 20)
        brroll = round(roll)
        if 9 < brroll < 101:
            bravery = round((brroll + Spirit) / 2)
            bcheck = 1

    Health = round(((Endurance * 2) + Spirit) / 3)
    Max_Hench = (2 ** round((Charisma - 10) / 11.25))
    Reactions = round((Agility + Cunning) / 2)
    Stealth = round((Spirit + Agility) / 2)
    Time_Units = round((Endurance + Agility) / 2)

    Luck_roll = random.randint(1, 20) - 15

    if Luck_roll < 0:
        Luck_roll = 0

    Luck = Luck_roll

    stat_block_second = [int(bravery), int(Health), int(Max_Hench), int(Reactions), int(Stealth), int(Time_Units),
                         int(Luck)]

    print("Secondary Stats\n")
    print("Bravery: ", bravery)
    print("Health: ", Health)
    print("Maximum Henchmen: ", Max_Hench)
    print("Reactions: ", Reactions)
    print("Stealth: ", Stealth)
    print("Time Units: ", Time_Units)
    print("Luck: ", Luck)
    print("")
    print("")

    # combat stats

    melee_accuracy = round(((Strength + Agility) / 2) - 50)
    melee_damage = round(Strength - 50)
    ranged_accuracy = round(Agility - 50)
    ranged_damage = round(((Strength + Agility) / 2) - 50)
    defense = Agility
    Mystic_Acumen = round((Cunning * 2 + Spirit) / 3)
    Mystic_Fortitude = round((Spirit * 2 + Cunning) / 3)

    stat_block_combat = [int(melee_accuracy), int(melee_damage), int(ranged_accuracy), int(ranged_damage), int(defense),
                         int(Mystic_Acumen), int(Mystic_Fortitude)]

    print("Combat Stats:\n")
    print("Melee Accuracy: ", melee_accuracy)
    print("Melee Damage: ", melee_damage)
    print("Ranged Accuracy: ", ranged_accuracy)
    print("Ranged Damage: ", ranged_damage)
    print("Defense: ", defense)
    print("Mystic Acumen: ", Mystic_Acumen)
    print("Mystic Fortitude: ", Mystic_Fortitude)
    print("\nLets send them to their death!\n\n")

    print(stat_block_prime)
    print(stat_block_second)
    print(stat_block_combat)

    knt01 = Knight(knight, stat_block_prime, stat_block_second, stat_block_combat)
    knight_counter = knight_counter + 1


"""def place_knight_into_class():
    knt01 = Knight(knight, 0, 1, 2)
    # knight_counter = knight_counter + 1
    print(knt01.name)
    print(knt01.statbp) 
This was to verify that the data was successfully added to the class"""


def population_inventory():

    """This function prints the current lists of knights and citizens."""

    print("")
    print("Remaining Citizens: ", citizen_names)
    print("Knights: ", knighted_members)


"""Here is where the main program begins."""

population_generation()

while promotion == "Yes":

    population_inventory()

    knight = input("\nWhom would you like to indoctrinate? ")

    check = knight in citizen_names

    if check == True:

        knighted_members.append(knight)
        citizen_names.remove(knight)

        print("")
        print(knight + " has been successfully purified, here are their knightly attributes:")

        knight_stat_gen()

        # place_knight_into_class()

        promotion = input("Is there anyone else you would like to promote? Yes or No: ")

    else:
        print("\nYou must choose from the available candidates.")


population_inventory()
Also I have hundreds of names in the name lists, I just shortened them for this post.

The area in question is at line 141.

Thank you, buran, for your suggestion. I will put some thought into moving in that direction. I think I would have to scrap most of what I have so far to do that, but, like I said, I don't know what I'm doing, so this is a good time to scrap and start over.

In the mean time, if possible, I would like to try getting this version to work.

Also, now that the code is out there, I am open to general feedback as well.

Again, thank you for your time.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020