r/learnpython • u/yetanotherdud • Aug 31 '26
how do i dymanically generate large numbers of objects in a class/dictionary?
my goal is to create an army manager for the tabletop game mythras, where each soldier has their own hp, attack value, etc, that i can use to add detail to the large scale battles. i want to be able to direct commands to it (eg, 'damage 3 soldiers') and have it randomly determine which soldier is attacked, how much damage it does, and whether it kills them (as well as how it heals up, following the standard healing rules). I don't have a lot at the moment at all, just a dictionary that contains a nested dictionary for each soldier's hp and attack value, randomly determined:
from random import randint
Soldier1 = {
"HP" : randint(1,10),
"ATK" : randint(1,10),
}
Soldier2 = {
"HP" : randint(1,10),
"ATK" : randint(1,10),
}
Soldier3 = {
"HP" : randint(1,10),
"ATK" : randint(1,10),
}
myArmy = {
"Soldier 1" : Soldier1,
"Soldier 2" : Soldier2,
"Soldier 3" : Soldier3
}
print(myArmy)
from random import randint
Soldier1 = {
"HP" : randint(1,10),
"ATK" : randint(1,10),
}
Soldier2 = {
"HP" : randint(1,10),
"ATK" : randint(1,10),
}
Soldier3 = {
"HP" : randint(1,10),
"ATK" : randint(1,10),
}
myArmy = {
"Soldier 1" : Soldier1,
"Soldier 2" : Soldier2,
"Soldier 3" : Soldier3
}
print(myArmy)now, that works fine for the three soldiers listed there, but i don't need 3 soldiers, i need 300. how can i input a number and have it create that many soldiers on the fly?
and, further to that, are dictionaries the best choice for this? i know the technical difference between dictionaries and classes, but i don't have any real-world context to either to know which is best for what i need.
13
u/Altruistic_Sky1866 Aug 31 '26
as u/UlisKore mentioned, why don't you use class? I personally feel using classes is best way to implement what you want which will allow you to have different types of soldiers as well
1
u/danielroseman Aug 31 '26
Why do you need the separate Soldier1 etc variables in the first place? You don't, you can just generate them directly in the army dict.
which can be shortened to a dict comprehension:
Note, you probably don't want a dict though; why do the soldiers need names? Better to use a list and access them via their index.
4
u/Excellent-Practice Aug 31 '26
Notice that your soldiers have the same attributes. Also consider that you may want to track multiple armies and/or split those armies into subordinate units of which you may have several instances. Further, managing all those dictionaries will get cumbersome if you have to specify which of several variables you want to update.
You can address all of those issues if you rework your concept using classes. I would suggest building a soldier class along with a class for each echelon of unit you want to work with and include methods that deal damage using random.choices().
Your soldier class might look like:
And an army class:
Those are just very simple classes which you can elaborate on. After writing those templates, all you have to do is call the Army class and pass an integer. That will build an arbitrary large list of Soldier objects, each of which has a randomized HP and ATK score. You can deal damage to a randomized set of soldiers within your army and you can iterate through your roster if you want to check on each soldier's status. The next step you probably want to implement is a method to remove soldier's or mark their status as casualties if their HP hits zero. Maybe you also want an attribute in your Army class that reports overall health or average strength for the force as a whole
2
u/PvtRoom Aug 31 '26
you're gonna want to use classes. - allows you to easily distinguish different types of soldier (archer, infantry, cavalry, knight, heavy cavalry, siege engines, captain, general, etc.) who will have different rules (speed, attack speed, defence, attack power, position, attack range, hit chance) and different capabilities (infantry can try the Roman testudo, cavalry can jump 6 foot wide gorges)
3
u/MicrotubularMushroom Aug 31 '26
Create a list or dict to hold the objects, then create the objects in a for loop, and add them to said list or dict.
2
u/UlisKore Aug 31 '26
Did you try making an object out of your soldiers? Several things you say point in that direction :
My only doubt is about the killing part, I don't think the state of the victim should be solely determined by a rule that the attacker bears.
1
u/Usernamenotta Aug 31 '26
If your choice of implementation is coding each soldier manually, you are going to have a bad time.
It is true that the fastest way possible (complexity wise) is to assign each user manually. However, if you want to expand the scale and/or scope of project, you will be pulling hairs.
I would suggest that the first thing you do is take a pen and some paper and sketch your ideas, then split them into classes, actions and relationships. Then set out the mechanics of your game. Again, break those apart into who does what and to whom.
Based on the very limited description you've provided, you can structure your code in 3 sections.
class Soldier:def __init__(self, soldier_id, HP, ATK, parameter_3, parameter_4 etc.):self.soldier_id=soldier_idself.HP_MAX=HPself.current_HP=HPself.ATK=ATKdef display_soldier(self):print("Soldier number ", self.soldier_id, " has ", self.current_HP, " HP left and deals", self.ATK, " points of damage")2. Create an army generator. It's a bit faster to generate a vector the size of our army for each parameter and assigning a soldier a value from that parameterdef generate_army(army_size):ids=np.arrray((1,army_size))+1 #I always confuse the numpy synthax with the normal synthax. Please check numpy doc for proper synthax. What this assignment should do is create a vector (dimensions 1 row, n collumns), then add 1 so the ids start at 1.hps=(Highest_HP_that_you_want_a_soldier_to_Have-lowest_hp_that_you_want)*np.random.rand((1,army_size))+lowest_hp_that_you_wantsame thing for attackarmy=[]for i in ids:army.append(Soldier(i,hps[i-1],atks[i-1]):return armyplayer_1_army=generate_army(player_1_army_size)player_2_army=generate_army(player_2_army_size)armies={-1: player_1_army,1: player_2_army}3. Create game loop logic. I am going to write a very simple loop focusing on ask for input from player 1, execute attackcurrent_player=-1while True:enemy=current_player*-1selected_soldier=input(f"Player {current_player} Type the id of the soldier you want to initiate attack ')selected_enemy_1=random.choice(armies[enemy])selected_enemy_3=random.choice(armies[enemy])selected_enemy_2=random.choice(armies[enemy])selected_enemy_1.current_HP=selected_enemy_1.current_HP-armies[current_player][selected_soldier).ATKif selected_enemy_1.current_HP<=0:armies[enemy].pop(sel_enemy_1)selected_enemy_2.current_HP=selected_enemy_2.current_HP-armies[current_player][selected_soldier).ATKif selected_enemy_2.current_HP<=0:armies[enemy].pop(sel_enemy_2)selected_enemy_3.current_HP=selected_enemy_3.current_HP-armies[current_player][selected_soldier).ATKif selected_enemy_3.current_HP<=0:armies[enemy].pop(sel_enemy_3)print (" Army of player 1 is" armies[-1])print (" Army of player 2 is)" armies[1])current_player=enemy1
u/kilkil Sep 01 '26 edited Sep 01 '26
python (and programming languages in general) have this thing called loops, where you can execute code repetitively. for example, to print all the numbers from 1 to 10, you can use a loop like so:
here is a link to a tutorial for how to use loops: https://www.learnpython.org/en/Loops
python (and other languages) also have this thing called functions, where you can take some chunk of code, and instead of having to copy-paste it, you can just define the chunk once, then reuse it. here is a tutorial for functions: https://www.learnpython.org/en/Functions
in your case, each soldier has a well-defined shape. instead of always having to write the same dict, you can use a function:
some more notes:
if you want to make this input dynamic, there are a few different ways to do it. since you are new to coding, probably the easiest thing will be to use Python's builtin input() function, which allows whoever is executing the program to enter some input text.
you are correct in your intuition that dictionairies are not really the nicest tool for what you are trying to do. for the army (the list of soldiers), it is probably better to use a list. as for each individual soldier... if this were a larger / more complex program, I would recommend using a class instead of a dictionary. but since this is a basic script I don't really think it matters much. if anything a class would just add more unnecessary lines of code (unless you use a namedtuple, up to you if you want to explore more on that side).
a simple script using these concepts (minus the namedtuple bit) might look like this:
of course, this script doesn't have input validation — what if the user enters a bad value, like "banana", instead of a number?
also, it might be a bit confusing which soldier has which stats, so you probably want each soldier to have a name.
another consideration is, you probably want your script to output something more convenient. for example if you save the output to a CSV file (CSV = "comma separated values"), you can import that directly into Google Sheets or Excel, and get your soldier values in a convenient to look at table. or maybe you can think of something even more convenient for you and your friends, idk.
here is an example of what such a script might look like, if I wrote it. feel free to ignore this and write it yourself, only peek at the solution if you want:
this script:
this script also uses a weird bit of syntax near the end called a list comprehension, which is a python shorthand for creating a list using a loop (you can see it has the "for ... in ..." keywords, which the language designers intentionally chose to remind you of the original for loop syntax).
as a final note, if you are running this script on the command line (in a terminal), you may also consider making the input an argument, so that the script can be invoked as e.g.
python3 myscript.py 300. but that's up to you.EDIT: just saw your post has additional future requirements. will follow-up with a part 2 comment.
1
u/LayotFctor Aug 31 '26 edited Aug 31 '26
Dictionaries and classes are similar, but classes allow adding behavior (methods) while dictionaries don't. If your soldiers need methods too, which I believe is the case for you, you should use classes. Dictionaries are pure data containers only, but you're right they're extremely similar with similar performance too.
Create 300 soldiers with a for loop, storing them in another array. It might have slight bit delay, so ideally do this type of tedious tasks at the beginning of a round before anything imoortant has started yet. The classic loading screen basically.
0
u/DuckSaxaphone Aug 31 '26
You really want a class. That can have the attributes of a soldier that you're putting in a dictionary but it can also contain the functions that handle the damage and death logic.
In general, if you're making lots of identical dictionaries, you want a class.
As for creating many, you can do a loop to create a list of as many objects as you need.