Waterbin
Waterbin

Reputation: 23

Getting a random choice from an array

I tried using the random.choice command and it seems to not work. The Wolf has already been assigned to mob

class Wolf(Character):
    def __init__(self):
        super().__init__(name="wolf",hp=7,atk=6,df=4,inventory={},spells= 
{"bite": randint(3,6)},exp=8)

c = random.choice(mob.spells)            
spower = mob.spells[c]          
ad = mob.atk / hero.df          
damage = ad * spower          
damage = int(round(damage))

Upvotes: 0

Views: 34

Answers (1)

JoshuaCS
JoshuaCS

Reputation: 2624

random.choice wont work because you are passing a dictionary and it expects something that can be indexed using integer indices. Choosing randomly from a dictionary could work if the keys are integers.

d = {'a': 10, 'b': 20}
random.choice(d)

The above code will fail, but this will work:

d = {1: 10, 0: 20}
random.choice(d)

Its not magic, it works because the code in random.choice chooses a random integer between 0 and len(obj) and return the object at that index. The code below will never work:

d = {-1: 10, 2: 20}
random.choice(d)

And this will work sometimes:

d = {'a': 10, 0: 20}
random.choice(d)

It doesnt make any sense to find a random index in a dictionary.

For getting a random key in a dictionary do this:

d = {'a': 10, -1: 20, 90: -90}
random_key = random.choice(list(d))

In your case, the code will be:

c = random.choice(list(mob.spells))

Upvotes: 1

Related Questions