Manuel Pepe
Manuel Pepe

Reputation: 93

Create an instance of a random class

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?

Upvotes: 1

Views: 3195

Answers (3)

Amber
Amber

Reputation: 526683

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.

Upvotes: 1

donkopotamus
donkopotamus

Reputation: 23186

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

Upvotes: 4

L3viathan
L3viathan

Reputation: 27283

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

Upvotes: 1

Related Questions