Home > Blockchain >  Python- Getting a random object from a list based on attribute
Python- Getting a random object from a list based on attribute

Time:07-16

For a python role-playing game, I am trying to randomly grab a monster from a list of objects based on the player object's attribute 'self.level'. Eventually, I will have over 100 unique monsters. Currently I have something like,

MONSTERS =[Kobold,... Skeleton,... Orc,.. Minotaur,.. Spector,... Wraith,... Balrog, Dragon]
monster_cls = random.choice(MONSTERS)

I want the 'monster.challenge_rating' to correspond roughly to the player's level- within a level or two. Currently I am using:

monster.challenge_rating = player_1.level   random.randint(0, 2)

Originally, I was simply upping the monster.challenge_rating of each monster to correspond to the player_1.level But, in order to add depth to the game, I was planning on making a list of objects for each challenge rating level, like,

monster_cr_1 = [rat, spider, flying snake..]
monster_cr_2 = [giant rat, giant spider...]
monster_cr_3 = [Kobold, Skeleton.....]
monster_cr_4 = [Drow, Orc, Mummy, Ghoul]
..
monster_cr_20 = [Balrog, Red Dragon, Kraken,...] 

I don't want to do:

if player_1.level == 1:
    random.choice(monster_cr_1)
if player_1.level == 2:
    random.choice(monster_cr_2)...

The maximum player level will be 20, so I know I will end up with many, many if statements. So, I attempted to grab it by appending the attribute to the end of a string. Something like:

monster = "monster_cr_", player_1.level
monster_cls = random.choice(monster)

But, I get all kinds of str object not callable and type errors. Is there a syntax that makes this possible? Is there a better way to do what I want that remains somewhat 'human readable' ? Thank you!

CodePudding user response:

You could use a dictionary.

import random


monsters = {
    1: ['rat', 'spider', 'flying snake'],
    2: ['giant rat', 'giant spider', 'kobold'],
    3: ['drow', 'orc', 'mummy']
}

player_level = 1
monster = random.choice(monsters[player_level])
  • Related