1

i'm currently making a text-based game on python and i have a question. I have classes for some rooms like RoomSpider, RoomSoldier, RoomDragon, etc. and I want to create a map (3d array) and fill some rooms with an instance of a random class.

For example:

[[RoomSpider, RoomSoldier],
[RoomSoldier,RoomDragon]]

How can I do to create an instance of a random class?

donkopotamus
  • 22,114
  • 2
  • 48
  • 60
Manuel Pepe
  • 93
  • 1
  • 6
  • Looking for this http://stackoverflow.com/questions/4821104/python-dynamic-instantiation-from-string-name-of-a-class-in-dynamically-imported ? – fghj Oct 28 '15 at 00:53

3 Answers3

4

To make an instance of a random class:

import random
classes = (RoomSpider, RoomSoldier, RoomDragon, 
           RoomElephant, RoomPixie)

# choose a random class from the list and instantiate it
instance = random.choice(classes)()
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
  • How about classes with arguments? What if it randomly chose one class which has more arguments than the others? – Alteros Sep 01 '20 at 02:11
  • @Alteros Using this approach then either all your classes need to expose a common constructor api (using `*args` or `**kw` if required), or you'll need factory functions with a common api – donkopotamus Sep 01 '20 at 05:02
1

Take a look at random.choice, it lets you choose a random element from a sequence.

from random import choice
classes = (RoomSpider, RoomSoldier, RoomDragon, ...)
room = [[choice(classes)() for _ in range(2)] for __ in range(2)]
L3viathan
  • 26,748
  • 2
  • 58
  • 81
1

Classes are first-class objects in Python, which means that you can store them in variables and pass them around. So for instance, you could make a list/tuple of all your possible classes and then pick random ones:

import random

room_classes = (RoomSpider, RoomSoldier, RoomDragon)
room_map = []

for row in range(5):
    room_row = []
    for col in range(5):
        room_class = random.choice(room_classes) # picks a random class
        room_row.append(room_class())            # creates an instance of that class
    room_map.append(room_row)

This uses random.choice() to generate a 5x5 set of randomly chosen instances.

Amber
  • 507,862
  • 82
  • 626
  • 550