Reputation: 419
I am working on a game where I need to randomly generate classes for a list. I use a self-made function randList
to do this. The code for that function looks like this:
def randList(options, num): #RANDOMLY SELECTS NUM ITEMS FROM LIST OPTIONS
returnVal = [] #CREATE A LIST THAT IT RETURNS
for i in range(num - 1): #FOR DESIRED NUMBER OF RETURN ITEMS
val = r.choice(options) #RANDOMLY SELECT ITEM FROM OPTIONS
returnVal.append(val) #ADD THAT TO RETURNVAL
options.remove(val) #REMOVE IT FROM OPTIONS.
return returnVal #RETURN GENERATED LIST
I am using that to randomly generate monsters and items in a room like so:
class roomParent: #ROOM CHARACTER FINDS
def __init__(self, entities, floor): #INIT WITH ENEMIES IN ROOM, ITEMS ON FLOOR
self.entities = entities #ENEMIES THERE ARE
self.floor = floor #ON FLOOR THERE IS
def generate(self):
global enemiesBeat
if enemiesBeat >= 500:
self.entities = [dragon]
else:
self.entities = randList([goblin, dwarf, slime, naga, troll, beholder], 1)
self.floor = randList([scrap, scrap, scrap, fireJar, ambrosia, sword, spearhead, armor, potion, slimeball], r.randint(0, 3))
room = roomParent([], [])
Just so you know, goblin
, dwarf
, slimeball
, etc. are defined earlier in the code. I don't think they have anything to do with the problem. I generate the room later like this:
def main():
room.generate()
print("Enemies: " + str(room.entities))
main()
I want it to print out a list with two random monsters in it from room.generate()
, but it always prints Enemies: []
. There are no errors in the code, and after trying to troubleshoot for 10 minutes, I decided to consult he web with no fruits in result of that labor. Thank you in advance for any help you give.
Upvotes: 2
Views: 188
Reputation: 1114
Use the random.sample library function.
Also, you might want to rethink your capitalization...snake_case is preferred over inCaps for function names.
Upvotes: 2
Reputation: 9076
As Oliver points out, the reason you get always get an empty entities
array is because self.entities
is set to randList([goblin, dwarf, slime, naga, troll, beholder], 1)
within generate
(I assume the global variable enemiesBeat
is less than 500 in your tests).
In your randList
function you have an off-by-one error that I mention in the comments which means that the generated list will contain one fewer items than specified by num
. As you try to generate a singleton list for self.entities
(num
= 1), you'll actually have it assigned to an empty list.
You can correct this issue by changing for i in range(num - 1)
to for i in range(num)
in your randList
function.
As an aside, I don't think you need to pass entities
and floor
as parameters to the roomParent
constructor, since it doesn't seem to have any effect. Instead, you could modify the class definition:
class roomParent(object):
def __init__(self):
self.entities = []
self.floor = []
...
And instantiate it like this:
room = roomParent()
Upvotes: 3