def generate_world_and_events(world_obj=None):
    if world_obj is None:
        world_obj = world.World()

    try:
        rand_seed = float(world_obj.get("rand_seed"))
    except ValueError:
        rand_seed = numpy.random.random()
    except TypeError:
        rand_seed = numpy.random.random()

    rand_seed = math_helpers.set_rand_seed(rand_seed)
    world_obj.set("rand_seed", rand_seed)

    # Calculate Parents History
    family_events = []

    # Generate Father
    father_data = world_obj.get("family.father")
    father = world.Person(world_obj, data=father_data, gender="Male", role="Father")
    father.dna = father.get("dna", dna_helpers.generate_dna()[0], random_number=False)
    if not father.get("family_name", None):
        father.create_name(create_new_last=True)
    message = father.name + " (Father) was born in " + str(father.birth_year)
    event_data = {
        "id": -2,
        "year": father.birth_year,
        "message": message,
        "significance": 0,
        "people": world_obj.people_copy,
    }
    family_events.append(event_data)

    # Generate Mother
    mother_data = world_obj.get("family.mother")
    mother = world.Person(world_obj, data=mother_data, gender="Female", role="Mother")
    mother.dna = mother.get("dna", dna_helpers.generate_dna()[0], random_number=False)
    if not mother.get("family_name", None):
        mother.create_name(create_new_last=True)
    message = mother.name + " (Mother) was born in " + str(mother.birth_year)
    event_data = {
        "id": -1,
        "year": father.birth_year,
        "message": message,
        "significance": 0,
        "people": world_obj.people_copy,
    }
    family_events.append(event_data)

    if father.age > mother.age:
        start_sim_year = int(world_obj.year - father.age + world_obj.age_of_consent)
    else:
        start_sim_year = int(world_obj.year - mother.age + world_obj.age_of_consent)
    end_sim_year = int(world_obj.year + 30)

    world_starter_year = world_obj.year

    years_data = []

    event_id = 0
    for y in range(start_sim_year, end_sim_year):
        world_obj.set("year", y)

        for p in world_obj.people_objects:
            p.update_biorhythms()

        details = []
        # import ipdb; ipdb.set_trace()
        if mother.can_marry and father.can_marry:
            mother.get_married(father)
            father.get_married(mother)
            details.append(
                "Father (age " + str(father.age) + ") and Mother (age " + str(mother.age) + ") were married together"
            )

        elif mother.can_marry and mother.passion > 2:
            spouse = mother.get_married()
            details.append("Mother (age " + str(+mother.age) + ") was married to " + spouse.name)

        elif father.can_marry and father.passion > 2:
            spouse = father.get_married()
            details.append("Father (age " + str(father.age) + ") was married to " + spouse.name)

        elif not mother.married and mother.chance_to_have_child():
            child = mother.have_child(event_id=event_id)
            details.append(
                "Mother (age "
                + str(mother.age)
                + ") had a "
                + child.gender
                + " child ("
                + child.name
                + ") while unmarried"
            )
            birth_event = child.get("birth_event", None)
            if birth_event:
                details.append(birth_event.get("message"))

        elif not father.married and father.chance_to_have_child():
            child = father.have_child(event_id=event_id)
            details.append(
                "Father (age "
                + str(father.age)
                + ") had a "
                + child.gender
                + " child ("
                + child.name
                + ") while unmarried"
            )
            birth_event = child.get("birth_event", None)
            if birth_event:
                details.append(birth_event.get("message"))

        elif father.is_married_to(mother) and father.chance_to_have_child() and mother.chance_to_have_child():
            child = father.have_child(spouse=mother, event_id=event_id)
            details.append(
                "Father (age "
                + str(father.age)
                + ") and Mother (age "
                + str(mother.age)
                + ") had a "
                + child.gender
                + " child ("
                + child.name
                + ") while married together"
            )
            birth_event = child.get("birth_event", None)
            if birth_event:
                details.append(birth_event.get("message"))

        elif not mother.is_married_to(father) and mother.married and mother.chance_to_have_child():
            spouse = mother.spouse
            child = mother.have_child(spouse=spouse, event_id=event_id)
            message = (
                "Mother (age "
                + str(mother.age)
                + ") had a "
                + child.gender
                + " child ("
                + child.name
                + ") while married to ("
                + spouse.name
                + ")"
            )
            details.append(message)
            birth_event = child.get("birth_event", None)
            if birth_event:
                details.append(birth_event.get("message"))

        elif not father.is_married_to(mother) and father.married and father.chance_to_have_child():
            spouse = father.spouse
            child = father.have_child(spouse=spouse, event_id=event_id)
            message = (
                "Father (age "
                + str(father.age)
                + ") had a "
                + child.gender
                + " child ("
                + child.name
                + ") while married to ("
                + spouse.name
                + ")"
            )
            details.append(message)
            birth_event = child.get("birth_event", None)
            if birth_event:
                details.append(birth_event.get("message"))

        # Leave each other if things go poorly
        elif father.married and father.conscience < -3 and father.passion < -3 and not father.deceased:
            details.append("Father (age " + str(father.age) + ") left his family")
            father.leave_family()

        elif mother.married and mother.conscience < -4 and mother.passion < -4 and not mother.deceased:
            details.append("Mother (age " + str(mother.age) + ") left her family")
            mother.leave_family()

        math_helpers.dict_round_floats(father.output, places=3)
        math_helpers.dict_round_floats(mother.output, places=3)
        math_helpers.dict_round_floats(world_obj.world_data, places=1)

        # TODO: instead of list of events, return array of people with updates per year
        significance = 1
        if not len(details):
            significance = 0
            details.append("Nothing eventful occurred")

        event_data = {
            "id": event_id,
            "year": y,
            "message": ", ".join(details),
            "significance": significance,
            "people": world_obj.people[:],
        }

        family_events.append(event_data)
        event_id += 1

        years_data.append({"year": y, "events": details, "people": world_obj.people_copy})
        # End Sim loop

    world_obj.set("year", world_starter_year)

    # return family_events, world_obj.people
    return years_data
Example #2
0
 def mutate(self):
     math_helpers.set_rand_seed(self.rand_seed_next)
     self.dna = dna_helpers.mutate_dna(self.dna)
Example #3
0
def generate_world_and_events(world_obj=None):
    if world_obj is None:
        world_obj = world.World()

    try:
        rand_seed = float(world_obj.get('rand_seed'))
    except ValueError:
        rand_seed = numpy.random.random()
    except TypeError:
        rand_seed = numpy.random.random()

    rand_seed = math_helpers.set_rand_seed(rand_seed)
    world_obj.set('rand_seed', rand_seed)

    #Calculate Parents History
    family_events = []

    #Generate Father
    father_data = world_obj.get('family.father')
    father = world.Person(world_obj, data=father_data, gender='Male', role='Father')
    father.dna = father.get("dna", dna_helpers.generate_dna()[0], random_number=False)
    if not father.get("family_name", None):
        father.create_name(create_new_last=True)
    message = father.name + " (Father) was born in " + str(father.birth_year)
    event_data = {"id": -2, "year": father.birth_year, "message": message, "significance": 0, 'people': world_obj.people_copy}
    family_events.append(event_data)

    #Generate Mother
    mother_data = world_obj.get('family.mother')
    mother = world.Person(world_obj, data=mother_data, gender='Female', role='Mother')
    mother.dna = mother.get("dna", dna_helpers.generate_dna()[0], random_number=False)
    if not mother.get("family_name", None):
        mother.create_name(create_new_last=True)
    message = mother.name + " (Mother) was born in " + str(mother.birth_year)
    event_data = {"id": -1, "year": father.birth_year, "message": message, "significance": 0, 'people': world_obj.people_copy}
    family_events.append(event_data)

    if father.age > mother.age:
        start_sim_year = int(world_obj.year - father.age + world_obj.age_of_consent)
    else:
        start_sim_year = int(world_obj.year - mother.age + world_obj.age_of_consent)
    end_sim_year = int(world_obj.year + 30)

    world_starter_year = world_obj.year

    years_data = []

    event_id = 0
    for y in range(start_sim_year, end_sim_year):
        world_obj.set("year", y)

        for p in world_obj.people_objects:
            p.update_biorhythms()

        details = []
        # import ipdb; ipdb.set_trace()
        if mother.can_marry and father.can_marry:
            mother.get_married(father)
            father.get_married(mother)
            details.append("Father (age "+str(father.age)+") and Mother (age "+str(mother.age)+") were married together")

        elif mother.can_marry and mother.passion > 2:
            spouse = mother.get_married()
            details.append("Mother (age "+str(+mother.age)+") was married to " + spouse.name)

        elif father.can_marry and father.passion > 2:
            spouse = father.get_married()
            details.append("Father (age "+str(father.age)+") was married to " + spouse.name)

        elif not mother.married and mother.chance_to_have_child():
            child = mother.have_child(event_id=event_id)
            details.append("Mother (age "+str(mother.age)+") had a " + child.gender + " child (" + child.name + ") while unmarried")
            birth_event = child.get('birth_event', None)
            if birth_event:
                details.append(birth_event.get('message'))

        elif not father.married and father.chance_to_have_child():
            child = father.have_child(event_id=event_id)
            details.append("Father (age "+str(father.age)+") had a " + child.gender + " child (" + child.name + ") while unmarried")
            birth_event = child.get('birth_event', None)
            if birth_event:
                details.append(birth_event.get('message'))

        elif father.is_married_to(mother) and father.chance_to_have_child() and mother.chance_to_have_child():
            child = father.have_child(spouse=mother, event_id=event_id)
            details.append("Father (age "+str(father.age)+") and Mother (age "+str(mother.age)+") had a " + child.gender + " child (" + child.name + ") while married together")
            birth_event = child.get('birth_event', None)
            if birth_event:
                details.append(birth_event.get('message'))

        elif not mother.is_married_to(father) and mother.married and mother.chance_to_have_child():
            spouse = mother.spouse
            child = mother.have_child(spouse=spouse, event_id=event_id)
            message = "Mother (age "+str(mother.age)+") had a " + child.gender + " child (" + child.name + ") while married to ("+spouse.name+")"
            details.append(message)
            birth_event = child.get('birth_event', None)
            if birth_event:
                details.append(birth_event.get('message'))

        elif not father.is_married_to(mother) and father.married and father.chance_to_have_child():
            spouse = father.spouse
            child = father.have_child(spouse=spouse, event_id=event_id)
            message = "Father (age "+str(father.age)+") had a " + child.gender + " child (" + child.name + ") while married to ("+spouse.name+")"
            details.append(message)
            birth_event = child.get('birth_event', None)
            if birth_event:
                details.append(birth_event.get('message'))

        #Leave each other if things go poorly
        elif father.married and father.conscience < -3 and father.passion < -3 and not father.deceased:
            details.append("Father (age "+str(father.age)+") left his family")
            father.leave_family()

        elif mother.married and mother.conscience < -4 and mother.passion < -4 and not mother.deceased:
            details.append("Mother (age "+str(mother.age)+") left her family")
            mother.leave_family()

        math_helpers.dict_round_floats(father.output, places=3)
        math_helpers.dict_round_floats(mother.output, places=3)
        math_helpers.dict_round_floats(world_obj.world_data, places=1)

        #TODO: instead of list of events, return array of people with updates per year
        significance = 1
        if not len(details):
            significance = 0
            details.append("Nothing eventful occurred")

        event_data = {"id": event_id, "year": y, "message": ", ".join(details), "significance": significance,
                      "people": world_obj.people[:]}

        family_events.append(event_data)
        event_id += 1


        years_data.append({"year": y, "events": details, "people": world_obj.people_copy})
        #End Sim loop

    world_obj.set('year', world_starter_year)

    #return family_events, world_obj.people
    return years_data
Example #4
0
def create_random_name(world_data={}, override={}, pattern="", tags="", rand_seed=None,
                       modifications=0, set_random_key=True, tag_weight=.3, gender=""):
    # Build a pattern if it doesn't exist, based on time and asian/other influences - TODO: Expand these rules
    # Can do {"namefile":"european"} to force country

    if set_random_key:
        try:
            rand_seed = float(rand_seed)
        except Exception:
            rand_seed = numpy.random.random()
        rand_seed = math_helpers.set_rand_seed(rand_seed)
        set_random_key = False

    name_patterns = {}
    name_patterns['jon_snow'] = 'namefile:1,namefile|family:1'
    name_patterns['king_jon_snow_the_pierced'] = 'rank:.1,namefile:1,namefile|family:.7,adjective:.4:the'
    name_patterns['king_jon_tyrion_snow_of_winterfell'] = 'rank:.1,namefile:1,namefile:.2,namefile|family:.8,placefile:.4:of'
    name_patterns['jon_tyrion_snow'] = 'namefile:1,namefile:1,namefile|family:1'

    if not pattern:
        pattern = name_patterns[np.random.choice(name_patterns.keys(), 1)[0]]

        if 'year' in world_data:
            year = int(world_data.get('year', None))
            if year:
                if year < 1400:
                    if numpy.random.random() < .5:
                        pattern = name_patterns['king_jon_snow_the_pierced']
                    else:
                        pattern = name_patterns['king_jon_tyrion_snow_of_winterfell']
                elif year > 1900:
                    pattern = name_patterns['jon_snow']
                else:
                    pattern = name_patterns['jon_tyrion_snow']

    generated_item = create_random_item(world_data=world_data, override=override, pattern=pattern, tags=tags,
                                        rand_seed=rand_seed, set_random_key=set_random_key, tag_weight=tag_weight,
                                        name_length=22)

    #TODO: This isn't really working with name generators. First, it finds a file like
    #TODO: waves, then it looks for that namefile OR one that's male or female or family
    #TODO: The tags don't help if it's gender/family/subsearch

    for idx, generator in enumerate(generated_item.get('generators')):
        generator_parts = generator.split("|")
        generator = generator_parts[0]
        generator_restrictions = generator_parts[1:]

        if generator == "namefile" or generator == "placefile":
            filename = generated_item['name_parts'][idx]
            restrictions = [filename]
            if generator_restrictions:
                restrictions += generator_restrictions
            elif gender:
                restrictions.append(gender)
            names = list_of_names(file_sub_strings=restrictions, prefix_chance=0)

            if len(names):
                generated_item['name_parts'][idx] = names[0]

    generated_item['name_parts'] = name_part_fuzzer(generated_item['name_parts'], modifications)

    generated_item['name'] = generate_item_name(generated_item['prefixes'], generated_item['name_parts'], titleize=True)

    generated_item['pattern'] = pattern

    return generated_item
Example #5
0
def create_random_item(world_data={}, override={}, set_random_key=True, parse_dice=False,
                       pattern='adjective:.7,origin:.7,item:1,power:1:that,quirk:.9:and', tags="", rand_seed=None,
                       tag_weight=.3, name_length=200):
    # Build the random number seed
    if set_random_key:
        try:
            rand_seed = float(rand_seed)
        except Exception:
            rand_seed = numpy.random.random()
        rand_seed = math_helpers.set_rand_seed(rand_seed)
    note = ""

    pattern_list, pattern_probability, pattern_prefixes = turn_pattern_to_hash(pattern, override)

    new_pattern_list = []
    for p in pattern_list:
        p_parts = p.split("|")
        new_pattern_list.append(p_parts[0])

    component_types, component_tag_counts = breakout_component_types(world_data, tags, new_pattern_list)

    item_data = {}
    effects_data = []
    item_generators = []
    item_prefixes = []
    item_names = []
    properties = {}
    tags = []

    for idx, ctype in enumerate(pattern_list):
        ctype_filter = ctype
        ctype_parts = ctype.split("|")
        ctype = ctype_parts[0]

        if numpy.random.random() <= pattern_probability[idx]:
            if ctype in component_types:
                components = component_types.get(ctype)

                if override and ctype_filter in override:
                    # Use this component instead
                    component_name = override.get(ctype_filter)
                    component = {"name": component_name}
                    ctype_filter = 'overrode'

                else:
                    # Randomly pick a component
                    component_counts = component_tag_counts.get(ctype)

                    component_tag_probabilities = counts_to_probabilities(component_counts, padding=tag_weight)

                    option = numpy.random.choice(components, 1, p=component_tag_probabilities)
                    component = option[0]

                try:
                    text = component.get("name", "")
                except AttributeError:
                    component = model_to_dict(component)
                    text = component.get("name", "")

                if parse_dice:
                    text = math_helpers.parse_dice_text(text)

                item_prefixes.append(pattern_prefixes[idx])
                item_names.append(text)
                item_generators.append(ctype_filter)

                component_tags = component.get("tags", '')
                if component_tags and isinstance(component_tags, basestring):
                    component_tags = component_tags.split(',')
                component_tags = [c.strip().lower() for c in component_tags]
                tags += component_tags

                component_props = component.get("properties", {})
                if component_props and isinstance(component_props, dict):
                    properties = component_props
                    item_data = dict(item_data.items() + properties.items())

                component_effects = component.get("effects", [])
                if component_effects and isinstance(component_effects, list) and len(component_effects):
                    effect = component_effects
                    effects_data += effect

    item_name = generate_item_name(item_prefixes, item_names, try_for_max_length=name_length)

    item_return = dict(name=item_name, data=item_data, effects=effects_data, note=note, rand_seed=rand_seed,
                       prefixes=item_prefixes, name_parts=item_names, generators=item_generators,
                       tags=tags, properties=properties)
    return item_return
Example #6
0
def create_random_name(
    world_data={},
    override={},
    pattern="",
    tags="",
    rand_seed=None,
    modifications=0,
    set_random_key=True,
    tag_weight=0.3,
    gender="",
):
    # Build a pattern if it doesn't exist, based on time and asian/other influences - TODO: Expand these rules
    # Can do {"namefile":"european"} to force country

    if set_random_key:
        try:
            rand_seed = float(rand_seed)
        except Exception:
            rand_seed = numpy.random.random()
        rand_seed = math_helpers.set_rand_seed(rand_seed)
        set_random_key = False

    name_patterns = {}
    name_patterns["jon_snow"] = "namefile:1,namefile|family:1"
    name_patterns["king_jon_snow_the_pierced"] = "rank:.1,namefile:1,namefile|family:.7,adjective:.4:the"
    name_patterns[
        "king_jon_tyrion_snow_of_winterfell"
    ] = "rank:.1,namefile:1,namefile:.2,namefile|family:.8,placefile:.4:of"
    name_patterns["jon_tyrion_snow"] = "namefile:1,namefile:1,namefile|family:1"

    if not pattern:
        pattern = name_patterns[np.random.choice(name_patterns.keys(), 1)[0]]

        if "year" in world_data:
            year = int(world_data.get("year", None))
            if year:
                if year < 1400:
                    if numpy.random.random() < 0.5:
                        pattern = name_patterns["king_jon_snow_the_pierced"]
                    else:
                        pattern = name_patterns["king_jon_tyrion_snow_of_winterfell"]
                elif year > 1900:
                    pattern = name_patterns["jon_snow"]
                else:
                    pattern = name_patterns["jon_tyrion_snow"]

    generated_item = create_random_item(
        world_data=world_data,
        override=override,
        pattern=pattern,
        tags=tags,
        rand_seed=rand_seed,
        set_random_key=set_random_key,
        tag_weight=tag_weight,
        name_length=22,
    )

    # TODO: This isn't really working with name generators. First, it finds a file like
    # TODO: waves, then it looks for that namefile OR one that's male or female or family
    # TODO: The tags don't help if it's gender/family/subsearch

    for idx, generator in enumerate(generated_item.get("generators")):
        generator_parts = generator.split("|")
        generator = generator_parts[0]
        generator_restrictions = generator_parts[1:]

        if generator == "namefile" or generator == "placefile":
            filename = generated_item["name_parts"][idx]
            restrictions = [filename]
            if generator_restrictions:
                restrictions += generator_restrictions
            elif gender:
                restrictions.append(gender)
            names = list_of_names(file_sub_strings=restrictions, prefix_chance=0)

            if len(names):
                generated_item["name_parts"][idx] = names[0]

    generated_item["name_parts"] = name_part_fuzzer(generated_item["name_parts"], modifications)

    generated_item["name"] = generate_item_name(generated_item["prefixes"], generated_item["name_parts"], titleize=True)

    generated_item["pattern"] = pattern

    return generated_item
Example #7
0
def create_random_item(
    world_data={},
    override={},
    set_random_key=True,
    parse_dice=False,
    pattern="adjective:.7,origin:.7,item:1,power:1:that,quirk:.9:and",
    tags="",
    rand_seed=None,
    tag_weight=0.3,
    name_length=200,
):
    # Build the random number seed
    if set_random_key:
        try:
            rand_seed = float(rand_seed)
        except Exception:
            rand_seed = numpy.random.random()
        rand_seed = math_helpers.set_rand_seed(rand_seed)
    note = ""

    pattern_list, pattern_probability, pattern_prefixes = turn_pattern_to_hash(pattern, override)

    new_pattern_list = []
    for p in pattern_list:
        p_parts = p.split("|")
        new_pattern_list.append(p_parts[0])

    component_types, component_tag_counts = breakout_component_types(world_data, tags, new_pattern_list)

    item_data = {}
    effects_data = []
    item_generators = []
    item_prefixes = []
    item_names = []
    properties = {}
    tags = []

    for idx, ctype in enumerate(pattern_list):
        ctype_filter = ctype
        ctype_parts = ctype.split("|")
        ctype = ctype_parts[0]

        if numpy.random.random() <= pattern_probability[idx]:
            if ctype in component_types:
                components = component_types.get(ctype)

                if override and ctype_filter in override:
                    # Use this component instead
                    component_name = override.get(ctype_filter)
                    component = {"name": component_name}
                    ctype_filter = "overrode"

                else:
                    # Randomly pick a component
                    component_counts = component_tag_counts.get(ctype)

                    component_tag_probabilities = counts_to_probabilities(component_counts, padding=tag_weight)

                    option = numpy.random.choice(components, 1, p=component_tag_probabilities)
                    component = option[0]

                try:
                    text = component.get("name", "")
                except AttributeError:
                    component = model_to_dict(component)
                    text = component.get("name", "")

                if parse_dice:
                    text = math_helpers.parse_dice_text(text)

                item_prefixes.append(pattern_prefixes[idx])
                item_names.append(text)
                item_generators.append(ctype_filter)

                component_tags = component.get("tags", "")
                if component_tags and isinstance(component_tags, basestring):
                    component_tags = component_tags.split(",")
                component_tags = [c.strip().lower() for c in component_tags]
                tags += component_tags

                component_props = component.get("properties", {})
                if component_props and isinstance(component_props, dict):
                    properties = component_props
                    item_data = dict(item_data.items() + properties.items())

                component_effects = component.get("effects", [])
                if component_effects and isinstance(component_effects, list) and len(component_effects):
                    effect = component_effects
                    effects_data += effect

    item_name = generate_item_name(item_prefixes, item_names, try_for_max_length=name_length)

    item_return = dict(
        name=item_name,
        data=item_data,
        effects=effects_data,
        note=note,
        rand_seed=rand_seed,
        prefixes=item_prefixes,
        name_parts=item_names,
        generators=item_generators,
        tags=tags,
        properties=properties,
    )
    return item_return