I am trying to write a text adventure game and I need some help. | Sololearn: Learn to code for FREE!

+1

I am trying to write a text adventure game and I need some help.

I have created some objects (heroes) and I want them to be chosen randomly. But I don't know how to do that. Can someone help me please ? https://code.sololearn.com/cP1YFii5J5U4/?ref=app

5/19/2018 4:45:23 PM

Masquerade

7 Answers

New Answer

+3

You could put your heroes in a list and use random choice. Like this: import random h_choice = [Hero_1, Hero_2, Hero_3] x = random.choice(h_choice ) print(x)

+7

its because youre creating 3 instances of Heroes (hero_1 hero_2 hero_3) Everytime an instance is created, the __init__ function is called. If you know other languages, thats the constructor equivalent in Python

+7

+5

Dont know much python but the idea is if you can push them into a container and choose a random number from 0 to container's length - 1

+2

First off, great start! Selecting a random hero should be relatively easy. One way to do it would be: import random heroes = [Hero_1, Hero_2, Hero_3] player = random.choice(heroes) Hope this helps :)

+1

Aha ! thanks a lot guys. it's working. But there's something interesting happens when I put h_choice = ['Hero_1', 'Hero_2', 'Hero_3'] x = random.choice(h_choice ) print(x) inside the init function. The x gets printed thrice. Can someone explain me how and why ?

+1

oh ! I get it now. Thanks a lot Happy and everyone. :-)