Last active
August 29, 2015 14:03
-
-
Save efruchter/23754b0f3cc90b928633 to your computer and use it in GitHub Desktop.
A bag of random elements to pick from. Usage: when you want to guarantee that a random event will occur an exact number of times, but want a random ordering. Good for RPG A.I., as it will prevent the AI from picking the same move too many times, but still have a skewed random pick.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
# A bag of random elements to pick from. | |
# Usage: when you want to guarantee that a random | |
# event will occur, but want a random ordering. | |
class RandomBag: | |
# Build a bag. Fill it with counts using tuples | |
# [('attack', 3), ('flee', 1), ...] | |
def __init__(self, element_count_tuples=[]): | |
self.bag = [] | |
for element, count in element_count_tuples: | |
self.add(element, count) | |
# Add some number of elements to the bag | |
def add(self, element, amount=1): | |
self.bag += [element] * amount | |
# Pick a single element out of the bag | |
def pick(self, remove_after_pick=True): | |
if self.is_empty(): | |
return None | |
pick = random.sample(self.bag, 1)[0] | |
if remove_after_pick: | |
self.bag.remove(pick) | |
return pick | |
# Is the bag empty (bool) | |
def is_empty(self): | |
return len(self.bag) == 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment