简体   繁体   English

Python-根据属性从列表中获取随机对象

[英]Python- Getting a random object from a list based on attribute

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'.对于 python 角色扮演游戏,我试图根据玩家对象的属性“self.level”从对象列表中随机抓取一个怪物。 Eventually, I will have over 100 unique monsters.最终,我将拥有超过 100 个独特的怪物。 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.我希望“monster.challenge_rating”大致对应于玩家的等级——在一两级之内。 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.challenge_rating 以对应 player_1.level 但是,为了增加游戏的深度,我计划为每个挑战等级制作一个对象列表,例如,

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.最高玩家等级将是 20,所以我知道我最终会得到很多很多 if 语句。 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.但是,我得到了各种不可调用的 str 对象和类型错误。 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!谢谢!

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM