示例#1
0
	def Verify (cls, value: dict, lastChangeVersion: Version.Version = None) -> dict:
		if not isinstance(value, dict):
			raise Exceptions.IncorrectTypeException(value, "value", (dict,))

		if not isinstance(lastChangeVersion, Version.Version) and lastChangeVersion is not None:
			raise Exceptions.IncorrectTypeException(lastChangeVersion, "lastChangeVersion", (Version.Version, "None"))

		for valueKey, valueValue in value.items():  # type: str, bool
			if not isinstance(valueKey, str):
				raise Exceptions.IncorrectTypeException(valueKey, "value<Key>", (str,))

			if not isinstance(valueValue, bool):
				raise Exceptions.IncorrectTypeException(valueValue, "value[%s]" % valueKey, (str,))

		return value
示例#2
0
文件: Sims.py 项目: NeonOcean/S4.Main
def HasTraitByID(simInfo: sim_info.SimInfo, traitID: int) -> bool:
    if not isinstance(simInfo, sim_info.SimInfo):
        raise Exceptions.IncorrectTypeException(simInfo, "simInfo",
                                                (sim_info.SimInfo, ))

    if not isinstance(traitID, int):
        raise Exceptions.IncorrectTypeException(traitID, "traitID", (int, ))

    for simTrait in simInfo.get_traits():
        if hasattr(simTrait, "guid64"):

            if simTrait.guid64 == traitID:
                return True

    return False
示例#3
0
	def PreRelease (self, value: typing.Tuple[typing.Union[int, str], ...]) -> None:
		if not isinstance(value, tuple):
			raise Exceptions.IncorrectTypeException(value, "PreRelease", (tuple,))

		for preReleaseIdentifierIndex in range(len(value)):  # type: int
			preReleaseIdentifier = value[preReleaseIdentifierIndex]  # type: typing.Union[str, int]

			if not isinstance(preReleaseIdentifier, (str, int)):
				raise Exceptions.IncorrectTypeException(value, "PreRelease[%s]" % preReleaseIdentifierIndex, (str, int))

			if isinstance(preReleaseIdentifier, str):
				if not self.ValidStringIdentifier(preReleaseIdentifier):
					raise ValueError("'PreRelease[%s]' contains a character outside what is allowed (0-9, A-Z, a-z, or -).\nValue: %s" % (preReleaseIdentifierIndex, preReleaseIdentifier))

		self._preRelease = value
示例#4
0
    def SetAllBranches(self,
                       key: str,
                       value,
                       autoSave: bool = True,
                       autoUpdate: bool = True) -> None:
        """
		Set the value of the persistent data specified by the key in all branches. The value is deep copied before being but into storage, modifying the value after
		setting it will not change the stored version.

		:param key: The name of the persistent data, is case sensitive.
		:type key: str
		:param value: The value the persistent data will be changing to. This must be of the type specified for the target persistent data during setup.
		:param autoSave: Whether or not to automatically save the persistent data after changing the value.
		 				 This can allow you to change multiple values at once without saving each time.
		:type autoSave: bool
		:param autoUpdate: Whether or not to automatically update callbacks to the fact that a value has changed.
						   This can allow you to change multiple values at once without calling update callbacks each time.
		:type autoUpdate: bool
		:rtype: None
		"""

        if not isinstance(key, str):
            raise Exceptions.IncorrectTypeException(key, "key", (str, ))

        if not self.IsSetup(key):
            raise Exception("Persistent data '" + key + "' is not setup.")

        valueStorage = self._storage[key]

        if not isinstance(value, valueStorage.ValueType):
            raise Exceptions.IncorrectTypeException(value, "value",
                                                    (valueStorage.ValueType, ))

        if not isinstance(autoSave, bool):
            raise Exceptions.IncorrectTypeException(autoSave, "autoSave",
                                                    (bool, ))

        if not isinstance(autoUpdate, bool):
            raise Exceptions.IncorrectTypeException(autoUpdate, "autoUpdate",
                                                    (bool, ))

        valueStorage.SetAllBranches(value, self.CurrentVersion)

        if autoSave:
            self.Save()

        if autoUpdate:
            self.Update()
示例#5
0
	def Decaying (self, reproductiveMinutes: typing.Union[float, int]) -> int:
		"""
		Get the amount of sperm cells that will decay within this many reproductive minutes. This may return a slightly incorrect value if the
		age or the input are between two game tick.
		"""

		if not isinstance(reproductiveMinutes, (float, int)):
			raise Exceptions.IncorrectTypeException(reproductiveMinutes, "reproductiveMinutes", (float, int))

		if reproductiveMinutes < 0:
			raise ValueError("The parameter 'reproductiveMinutes' cannot be less than 0.")

		if self.SpermCount == 0:
			return 0

		if reproductiveMinutes == 0:
			return 0

		currentAge = self.Age  # type: float
		nextAge = self.Age + reproductiveMinutes  # type: float

		if nextAge >= self.Lifetime:
			return self.SpermCount

		currentPercentageRemaining = 1.0 - self.LifetimeDistribution.CumulativeDistribution(currentAge)  # type: typing.Union[float, int]
		nextPercentageRemaining = 1.0 - self.LifetimeDistribution.CumulativeDistribution(nextAge)  # type: typing.Union[float, int]
		percentageRemainingChange = nextPercentageRemaining - currentPercentageRemaining  # type: typing.Union[float, int]

		originalSpermCount = int(self.SpermCount / currentPercentageRemaining)  # type: int
		decayingSpermCount = int(originalSpermCount * percentageRemainingChange)  # type: int

		if decayingSpermCount < 0:
			Debug.Log("Calculated a decaying sperm count of less than zero (%s)." % decayingSpermCount, This.Mod.Namespace, Debug.LogLevels.Warning, group = This.Mod.Namespace, owner = __name__, lockIdentifier = __name__ + ":" + str(Python.GetLineNumber()))

		return int(originalSpermCount * percentageRemainingChange)
示例#6
0
    def AddPoint(self, point: CurvePoint) -> None:
        if not isinstance(point, CurvePoint):
            raise Exceptions.IncorrectTypeException(point, "point",
                                                    (CurvePoint, ))

        self._points.append(point)
        self._SortPoints()
示例#7
0
    def ClosestPointIndex(self, x: float) -> int:
        """
		Get the index of the point with an x value closest to the input x value.
		"""

        if not isinstance(x, (float, int)):
            raise Exceptions.IncorrectTypeException(x, "x", (float, int))

        if len(self._points) <= 0:
            raise Exception("Cannot work on a curve with no points.")

        closestIndex = None  # type: typing.Optional[int]
        closestDistance = None  # type: typing.Union[float, None]

        for pointIndex in range(len(self._points)):  # type: int
            point = self._points[pointIndex]  # type: CurvePoint

            distance = abs(point.X - x)  # type: float

            if closestIndex is not None:
                if distance > closestDistance:
                    break

            closestIndex = pointIndex
            closestDistance = distance

            if point.X >= x:
                break

        assert closestIndex is not None

        return closestIndex
示例#8
0
文件: Save.py 项目: NeonOcean/S4.Main
def UnloadWithHost (host: Mods.Mod) -> None:
	"""
	Unload all registered and loaded saving objects with the specified host
	"""

	if not isinstance(host, Mods.Mod):
		raise Exceptions.IncorrectTypeException(host, "host", (Mods.Mod,))

	Debug.Log("Unloading all saving objects from the host '%s'" % host.Namespace, This.Mod.Namespace, Debug.LogLevels.Info, group = This.Mod.Namespace, owner = __name__)

	failedSavingIdentifiers = list()  # type: typing.List[str]

	for savingObject in _registeredSavingObjects:  # type: Saving.SaveBase
		try:
			if not savingObject.Host == host:
				continue

			if not savingObject.Loaded:
				continue

			savingObject.Unload()  # type: bool
		except Exception:
			Debug.Log("Encountered an unhandled exception upon unloading a saving object with the identifier '" + savingObject.Identifier + "'.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__)
			failedSavingIdentifiers.append(savingObject.Identifier)

	if len(failedSavingIdentifiers) != 0:
		_ShowModUnloadFailureDialog(failedSavingIdentifiers)

	Debug.Log("Finished unloading all saving object from the host '%s' and encountered %s error(s)." % (host.Namespace, str(len(failedSavingIdentifiers))), This.Mod.Namespace, Debug.LogLevels.Info, group = This.Mod.Namespace, owner = __name__)
示例#9
0
文件: Dot.py 项目: NeonOcean/S4.Cycle
	def Save (self, simsSection: SectionBranched.SectionBranched) -> bool:
		"""
		Save the reproductive system's data to this saving section. An exception will be raised if no valid sim has been set for this dot object.
		"""

		if self.TargetSimID is None or self.TargetSimInfo is None:
			raise Exception("Cannot save a dot information object with no target sim.")

		if not isinstance(simsSection, SectionBranched.SectionBranched):
			raise Exceptions.IncorrectTypeException(simsSection, "simsSection", (SectionBranched.SectionBranched,))

		if self.Outdated:
			self.Update()

		operationInformation = self.SavableOperationInformation  # type: str
		operationSuccessful = True  # type: bool

		try:
			targetSimSavingKey = Saving.GetSimSimsSectionBranchKey(self.TargetSimInfo)  # type: str

			saveSuccessful, dotInformationData = self.SaveToDictionary()  # type: bool, dict
			simsSection.Set(targetSimSavingKey, DotSavingKey, dotInformationData)
		except:
			Debug.Log("Save operation in a dot information object aborted.\n" + operationInformation, self.HostNamespace, Debug.LogLevels.Exception, group = self.HostNamespace, owner = __name__)
			return False

		if not saveSuccessful:
			return False

		return operationSuccessful
示例#10
0
    def HandlerRemovedEvent(self, value: Events.EventHandler) -> None:
        if not isinstance(value, Events.EventHandler):
            raise Exceptions.IncorrectTypeException(value,
                                                    "HandlerRemovedEvent",
                                                    (Events.EventHandler, ))

        self._handlerRemovedEvent = value
示例#11
0
    def LowerBound(self, value: typing.Optional[typing.Union[float,
                                                             int]]) -> None:
        if not isinstance(value, (float, int)) and value is not None:
            raise Exceptions.IncorrectTypeException(value, "LowerBound",
                                                    (float, int, None))

        self._lowerBound = value
示例#12
0
def GetAverageLifeSpan(
        species: sim_info_types.Species) -> typing.Union[float, int]:
    """
	Get the average life span of any member of this species.
	:param species: The species to get the average life span of.
	:type species: sim_info_types.Species
	:return: The average life span of any member of this species. This value will be unmodified by the game's lifespan settings, as if
	it was set to "normal".
	:rtype: typing.Union[float, int]
	"""

    if not isinstance(species, sim_info_types.Species):
        raise Exceptions.IncorrectTypeException(species, "species",
                                                (sim_info_types.Species, ))

    speciesAgingData = aging_tuning.AgingTuning.get_aging_data(
        species)  # type: aging_data.AgingData

    # noinspection PyUnresolvedReferences
    speciesAges = speciesAgingData.ages  # type: typing.Dict[sim_info_types.Age, aging_transition.AgingTransition]
    speciesLifeSpan = 0  # type: typing.Union[float, int]

    for speciesAge in speciesAges.values(
    ):  # type: aging_transition.AgingTransition
        # noinspection PyUnresolvedReferences, PyProtectedMember
        ageDurationInterval = speciesAge.transition._age_duration  # type: tunable.TunedInterval
        speciesLifeSpan += (ageDurationInterval.lower_bound +
                            ageDurationInterval.upper_bound) / 2

    return speciesLifeSpan
示例#13
0
    def IsHandlingLanguageSTBLFile(cls, stblInstanceHexID: str) -> bool:
        if not isinstance(stblInstanceHexID, str):
            raise Exceptions.IncorrectTypeException(stblInstanceHexID,
                                                    "stblInstanceHexID",
                                                    (str, ))

        return stblInstanceHexID.startswith(cls.STBLInstanceIDPrefix)
    def GenerateOvumDelay(
            self,
            strength: float,
            seed: typing.Optional[typing.Hashable] = None) -> float:
        """
		Generate a random ovum delay based on this strength value and using this seed.
		"""

        if not isinstance(strength, (float, int)):
            raise Exceptions.IncorrectTypeException(strength, "strength",
                                                    (float, int))

        if strength < 0 or strength > 1:
            raise ValueError(
                "The 'strength' parameter must be between 0 and 1.")

        effectGuide = self.EmergencyContraceptivePillEffectGuide  # type: CycleGuides.EmergencyContraceptivePillEffectGuide

        delayTimeMean = effectGuide.DelayTimeMean.Evaluate(
            strength)  # type: float
        delayTimeStandardDeviation = effectGuide.DelayTimeStandardDeviation.Evaluate(
            strength)  # type: float

        random.seed(seed)
        delayTimeDistribution = Distribution.NormalDistribution(
            mean=delayTimeMean, standardDeviation=delayTimeStandardDeviation
        )  # type: Distribution.NormalDistribution
        delayTime = delayTimeDistribution.GenerateValue(
            seed, minimum=0,
            maximum=effectGuide.DelayTimeMaximum)  # type: float

        return delayTime
示例#15
0
def Patch (originalObject: typing.Any, originalCallableName: str, targetFunction: typing.Callable, patchType: PatchTypes = PatchTypes.After, permanent: bool = False) -> None:
	"""
	Combine a function with another function or method, the original callable located in the original object will then be replaced by the patch automatically.
	:param originalObject: The object the original callable resides in.
	:type originalObject: typing.Any
	:param originalCallableName: The name of the callable to be combined, Can be a reference to a function, built in function, or method.
	:type originalCallableName: str
	:param targetFunction: The function object that will be combined with the original. This can only be a function or a built in function.
	:type targetFunction: typing.Callable
	:param patchType: Controls when the original callable is called. A value of PatchTypes.Custom requires that the target function take an extra argument
					  in the first argument position. The extra argument will be a reference to the original callable.
	:type patchType: PatchTypes
	:param permanent: Whether or not the patch will be disabled if the module the patching function resides in is unloaded.
	:type permanent: bool
	"""

	if originalObject is None:
		raise TypeError("originalObject cannot be none.")

	if not isinstance(originalCallableName, str):
		raise Exceptions.IncorrectTypeException(originalCallableName, "originalCallableName", (str,))

	originalCallable = getattr(originalObject, originalCallableName)  # type: typing.Callable

	if originalCallable is None:
		raise Exception("Cannot find attribute named '" + originalCallableName + "' in '" + Types.GetFullName(originalObject) + "'.")

	patchedFunction = PatchDirectly(originalCallable, targetFunction, patchType = patchType, permanent = permanent)
	setattr(originalObject, originalCallableName, patchedFunction)
示例#16
0
    def ShowCustomizeButton(self, value: bool) -> None:
        if not isinstance(value, bool):
            raise Exceptions.IncorrectTypeException(value,
                                                    "ShowCustomizeButton",
                                                    (bool, ))

        self._showCustomizeButton = value
示例#17
0
    def SelectAppropriateBuff(
        self, menstrualCycle: CycleMenstrual.MenstrualCycle
    ) -> typing.Tuple[typing.Optional[typing.Type[BuffsMenstrual.
                                                  MenstrualBuffBase]], bool]:
        """
		Randomly select an appropriate buff for target sim with a menstrual cycle in the input cycle's state.
		:param menstrualCycle: The menstrual cycle which we will look at to find appropriate buffs for the event's target sim.
		:type menstrualCycle: CycleMenstrual.MenstrualCycle
		:return: The selected buff type, if any, and a boolean indicating whether or not there where any valid buffs to select.
		"""

        if not isinstance(menstrualCycle, CycleMenstrual.MenstrualCycle):
            raise Exceptions.IncorrectTypeException(
                menstrualCycle, "menstrualCycle",
                (CycleMenstrual.MenstrualCycle, ))

        rarityChoice = self.SelectBuffRarity(
        )  # type: typing.Optional[BuffsShared.BuffRarity]

        if rarityChoice is None:
            return None, self._HasValidBuffType(menstrualCycle)
        else:
            validBuffs = self._GetValidBuffTypesWithRarity(
                rarityChoice, menstrualCycle
            )  # type: typing.List[typing.Type[BuffsMenstrual.MenstrualBuffBase]]

            if len(validBuffs) == 0:
                return None, self._HasValidBuffType(menstrualCycle)

            random.seed(self.Seed + -579905054)
            selectedBuffType = random.choice(
                validBuffs
            )  # type: typing.Type[BuffsMenstrual.MenstrualBuffBase]
            return selectedBuffType, True
示例#18
0
    def AddBuffRarityOptionAdjuster(
            self, option: str, adjuster: Probability.OptionAdjuster) -> None:
        if not isinstance(option, str):
            raise Exceptions.IncorrectTypeException(option, "option", (str, ))

        if not isinstance(adjuster, Probability.OptionAdjuster):
            raise Exceptions.IncorrectTypeException(
                adjuster, "adjuster", (Probability.OptionAdjuster, ))

        buffRarityOptionAdjusters = self._buffRarityOptionAdjusters.get(
            option, None)  # type: typing.List[Probability.OptionAdjuster]

        if buffRarityOptionAdjusters is None:
            self._buffRarityOptionAdjusters[option] = [adjuster]
        else:
            buffRarityOptionAdjusters.append(adjuster)
示例#19
0
    def ShowDialog(
        cls,
        returnCallback: typing.Optional[typing.Callable[[],
                                                        None]] = None) -> None:
        """
		Show the dialog to change this setting.
		:param returnCallback: The return callback will be triggered after the setting dialog is closed.
		:type returnCallback: typing.Callable[[], None]
		"""

        if not isinstance(returnCallback,
                          typing.Callable) and returnCallback is not None:
            raise Exceptions.IncorrectTypeException(returnCallback,
                                                    "returnCallback",
                                                    ("Callable", None))

        if not cls.CanShowDialog():
            return

        if cls.Dialog is None:
            return

        settingWrapper = UISettingsShared.SettingStandardWrapper(
            cls)  # type: UISettingsShared.SettingStandardWrapper
        settingDialog = cls.Dialog()  # type: UISettings.SettingDialogBase
        settingDialog.ShowDialog(settingWrapper, returnCallback=returnCallback)
示例#20
0
def GetLocalizationStringByIdentifier(
        identifier: str,
        *tokens,
        fallbackText: str = None) -> localization.LocalizedString:
    """
	Find localized string by identifier. No identifiers will be loaded until a zone is loaded.
	:param identifier: This function will look through the list or registered entries to find one with this identifier.
					   Case will be ignored while searching for the identifier.
					   If the corresponding identifier object cannot be found a localization string will be created containing the identifier.
	:type identifier: str
	:param tokens: Valid tokens include any object with a function called "populate_localization_token", numbers, strings, LocalizedString objects, and arrays.
	 			   Array tokens seem to be considered lists of sims and all objects inside them require the "populate_localization_token" function.

	:param fallbackText: The text that will be fallen back to if the specified identifier isn't registered. If this is None the identifier will be used instead.
	:type fallbackText: str

	:rtype: localization.LocalizedString
	"""

    if not isinstance(identifier, str):
        raise Exceptions.IncorrectTypeException(identifier, "identifier",
                                                (str, ))

    identifierObject = _GetIdentifierObject(_SplitIdentifier(identifier))

    if identifierObject.Key is not None:
        return GetLocalizationStringByKey(identifierObject.Key, *tokens)
    else:
        if fallbackText is None:
            return CreateLocalizationString(identifier)
        else:
            return CreateLocalizationString(fallbackText)
示例#21
0
    def __init__(self, seed: int, timeSinceLastCycle: typing.Optional[float],
                 *args, **kwargs):
        """
		Event arguments to test when the next cycle should start.
		:param seed: The seed used in the creation of random values for this event. The seed should be mixed with another number specific to each
		randomization operation, otherwise everything would generate the same numbers.
		:type seed: int
		:param timeSinceLastCycle: The amount of time in reproductive minutes since the last cycle ended. This will be None if no cycle has been
		simulated yet.
		:type timeSinceLastCycle: typing.Optional[float]
		"""

        if not isinstance(timeSinceLastCycle,
                          (float, int)) and timeSinceLastCycle is not None:
            raise Exceptions.IncorrectTypeException(timeSinceLastCycle,
                                                    "timeSinceLastCycle",
                                                    (float, int, None))

        super().__init__(seed, *args, **kwargs)

        self._timeSinceTest = 0  # type: float

        self._timeSinceLastCycle = timeSinceLastCycle  # type: typing.Optional[float]

        self._canStart = Tweakable.TweakableBoolean(
            True)  # type: Tweakable.TweakableBoolean
        self.StartingAt = None
示例#22
0
	def SelectPerformanceType (self, seed: typing.Optional[int] = None) -> typing.Tuple[str, PerformanceTypeInfo]:
		"""
		Randomly select one of the performance type in this woohoo safety method.
		"""

		if seed is None:
			seed = random.randint(-1000000000, 1000000000)  # type: int

		if not isinstance(seed, int):
			raise Exceptions.IncorrectTypeException(seed, "seed", (int, None))

		if len(self.PerformanceTypes) == 0:
			raise Exception("Could not find any safety method performance type to select.\nGUID: %s" % self.GUID)

		if len(self.PerformanceTypeChances.Options) == 0:
			raise Exception("Could not select a performance type 'PerformanceTypeChances' has no options.\nGUID: %s" % self.GUID)

		performanceType = self.PerformanceTypeChances.ChooseOption(seed = seed + -443757754).Identifier  # type: str
		performanceTypeInfo = self.PerformanceTypes.get(performanceType, None)  # type: WoohooSafetyMethod.PerformanceTypeInfo

		if performanceTypeInfo is None:
			Debug.Log("Randomly selected performance type that doesn't exist.\nGUID: %s, Performance Type: %s" % (str(self.GUID), performanceType), This.Mod.Namespace, Debug.LogLevels.Error, group = This.Mod.Namespace, owner = __name__)
			return random.choice(self.PerformanceTypes)

		return performanceType, performanceTypeInfo
示例#23
0
	def __init__ (self, options: typing.Union[typing.List[Option], typing.Tuple[Option, ...]]):
		"""
		An object to randomly select from a set of options.
		:param options: This object's set of options. Duplicate options in this list will not be added.
		:type options: typing.List[ProbabilityOption]
		"""

		if options is None:
			options = list()

		if not isinstance(options, (list, tuple)):
			raise Exceptions.IncorrectTypeException(options, "options", (list, tuple, None))

		super().__init__()

		self._options = list(options)

		self.RegisterSavableAttribute(Savable.ListedSavableAttributeHandler(
			"Options",
			"_options",
			lambda: Option("", 0),
			lambda: list(),
			requiredAttribute = True)
		)

		self._ClearDuplicateOptions()
示例#24
0
    def __init__(self, value: bool):
        if not isinstance(value, bool):
            raise Exceptions.IncorrectTypeException(value, "value", (bool, ))

        self._baseValue = value

        self.Locked = False

        self.Value = value

        super().__init__()

        self.RegisterSavableAttribute(
            Savable.StandardAttributeHandler("BaseValue",
                                             "_baseValue",
                                             0,
                                             requiredAttribute=True))
        self.RegisterSavableAttribute(
            Savable.StandardAttributeHandler("Value",
                                             "Value",
                                             0,
                                             requiredAttribute=True))
        self.RegisterSavableAttribute(
            Savable.StandardAttributeHandler("Locked",
                                             "Locked",
                                             False,
                                             requiredAttribute=True))
示例#25
0
def CloseDirectory (directoryPath: typing.Union[str, pathlib.Path], ignoreErrors: bool = False) -> None:
	"""
	If the specified directory exists and is empty it will be deleted.
	:param directoryPath: The path of the directory to closed.
	:type directoryPath: str
	:param ignoreErrors: Whether or not to ignore errors encountered while removing the directory.
	:type ignoreErrors: bool
	"""

	if not isinstance(directoryPath, str) and not isinstance(directoryPath, pathlib.Path):
		raise Exceptions.IncorrectTypeException(directoryPath, "directoryPath", (str, pathlib.Path))

	if isinstance(directoryPath, pathlib.Path):
		directoryPath = str(directoryPath)

	try:
		if not os.path.exists(directoryPath):
			return

		if os.path.isfile(directoryPath):
			return

		directoryContents = os.listdir(directoryPath)  # type: typing.List[str]
	except Exception if not ignoreErrors else Exceptions.DummyException:
		return

	if len(directoryContents) == 0:
		try:
			os.rmdir(directoryPath)
		except Exception if not ignoreErrors else Exceptions.DummyException:
			return
示例#26
0
    def RemoveSperm(self, removingSperm: Sperm.Sperm) -> None:
        """
		Remove already released sperm from this reproductive system. If the sperm object was never released nothing will happen.
		:param removingSperm: The sperm object to be removed.
		:type removingSperm: Sperm.Sperm
		"""

        if not isinstance(removingSperm, Sperm.Sperm):
            raise Exceptions.IncorrectTypeException(removingSperm,
                                                    "removingSperm",
                                                    (Sperm.Sperm, ))

        activeSpermIndex = 0
        while activeSpermIndex < len(self._activeSperm):
            activeSperm = self._activeSperm[
                activeSpermIndex]  # type: Sperm.Sperm

            if activeSperm == removingSperm:
                self._UnsetSpermCallbacks(activeSperm)
                self._activeSperm.pop(activeSpermIndex)

                if self.TrackingSystem.Simulating:
                    self.TrackingSystem.Simulation.NeedToPlan = True

            activeSpermIndex += 1
示例#27
0
	def IsAvailable (self, targetSimInfo: sim_info.SimInfo) -> bool:
		"""
		Get whether or not the target sim can use this safety method. This may incorrectly return false for non-instanced sims; we cannot read the inventory
		of sims not instanced.
		"""

		if not isinstance(targetSimInfo, sim_info.SimInfo):
			raise Exceptions.IncorrectTypeException(targetSimInfo, "targetSimInfo", (sim_info.SimInfo,))

		if not self.HasRequirement:
			return True

		if not targetSimInfo.is_instanced():
			return False

		targetSim = targetSimInfo.get_sim_instance()  # type: sim.Sim

		for requirementGroup in self.Requirements:  # type: typing.Tuple[WoohooSafetyMethod.Requirement, ...]
			if len(requirementGroup) == 0:
				continue

			groupRequirementsMet = True  # type: bool

			for requirement in requirementGroup:  # type: WoohooSafetyMethod.Requirement
				if not requirement.RequirementMet(targetSim):
					groupRequirementsMet = False
					break

			if groupRequirementsMet:
				return True

		return False
示例#28
0
def ShowObjectPickerDialog (callback: typing.Callable = None, pickerRows: list = None, **dialogArguments) -> None:
	"""
	:param callback: Called after the dialog gets a response from the user. This will never be called it the dialog has no responses.
	 				 The callback function will receive one argument; a reference to the dialog.
	:type callback: typing.Callable

	:param pickerRows: A list of picker row objects sent to the dialog.
	:type pickerRows: list
	"""

	if not isinstance(callback, typing.Callable) and callback is not None:
		raise Exceptions.IncorrectTypeException(callback, "callback", ("Callable",))

	if not "owner" in dialogArguments:
		activeSim = services.get_active_sim()  # type: sim.Sim

		if activeSim is None:
			raise Exception("Cannot find active sim, object picker dialogs cannot be opened without a sim tied to them through the 'owner' value.")

		dialogArguments["owner"] = activeSim.sim_info

	dialog = ui_dialog_picker.UiObjectPicker.TunableFactory().default(**dialogArguments)  # type: ui_dialog_picker.UiObjectPicker

	if pickerRows is not None:
		for pickerRow in pickerRows:
			dialog.add_row(pickerRow)

	if callback is not None:
		dialog.add_listener(callback)

	dialog.show_dialog()
示例#29
0
		def RequirementMet (self, targetSim: sim.Sim) -> bool:
			"""
			Whether or not the target sim meets the requirements.
			"""

			if not isinstance(targetSim, sim.Sim):
				raise Exceptions.IncorrectTypeException(targetSim, "targetSim", (sim.Sim,))

			if self.RequiredObject is None:
				return False

			inventoryComponent = targetSim.get_component(ComponentsTypes.INVENTORY_COMPONENT)  # type: ComponentsInventory.InventoryComponent

			if not inventoryComponent.has_item_with_definition(self.RequiredObject):
				return False
			else:
				if len(self.RequiredObjectTests) == 0:
					return True

			for matchingObject in inventoryComponent.get_items_with_definition_gen(self.RequiredObject):  # type: game_object.GameObject
				requiredObjectResolver = resolver.SingleObjectResolver(matchingObject)
				testResults = self.RequiredObjectTests.run_tests(requiredObjectResolver)  # type: typing.Optional[TestingUnit.TestResult]

				if not testResults:
					return False

			return True
示例#30
0
文件: Dot.py 项目: NeonOcean/S4.Cycle
	def __init__ (self, targetSimInfoOrID: typing.Union[sim_info.SimInfo, int, None]):
		"""
		An object to save information for and handle interactions with the dot menstrual cycle tracker app.
		"""

		if not isinstance(targetSimInfoOrID, (sim_info.SimInfo, int)) and targetSimInfoOrID is not None:
			raise Exceptions.IncorrectTypeException(targetSimInfoOrID, "targetSimInfoOrID", (sim_info.SimInfo, int, None))

		super().__init__()

		self._targetSimPointer = SimPointer.SimPointer()
		self._targetSimPointer.ChangePointer(targetSimInfoOrID)

		self._simulating = False  # type: bool

		self.Enabled = False
		self.TrackingMode = TrackingMode.Cycle
		self.ShowFertilityNotifications = False

		self.TimeSinceCycleStart = None

		self.LastSimulatedTick = services.time_service().sim_now.absolute_ticks()

		encodeEnum = lambda value: value.name if value is not None else None
		decodeTrackingMode = lambda valueString: Parse.ParsePythonEnum(valueString, TrackingMode)

		self.RegisterSavableAttribute(Savable.StandardAttributeHandler("Enabled", "Enabled", self.Enabled))
		self.RegisterSavableAttribute(Savable.StandardAttributeHandler("TrackingMode", "TrackingMode", self.TrackingMode, encoder = encodeEnum, decoder = decodeTrackingMode))
		self.RegisterSavableAttribute(Savable.StandardAttributeHandler("ShowFertilityNotifications", "ShowFertilityNotifications", self.ShowFertilityNotifications))
		self.RegisterSavableAttribute(Savable.StandardAttributeHandler("TimeSinceCycleStart", "TimeSinceCycleStart", self.TimeSinceCycleStart))