def show_unsuccessful_server_host(): title = "Nobody connected to the host in time." notification = UiDialogNotification.TunableFactory().default( services.get_active_sim(), title=lambda **_: LocalizationHelperTuning.get_raw_text(title)) notification.show_dialog(icon_override=(None, services.get_active_sim()))
def show_server_host_attempt(): title = "Attempting to host the game." notification = UiDialogNotification.TunableFactory().default( services.get_active_sim(), title=lambda **_: LocalizationHelperTuning.get_raw_text(title)) notification.show_dialog(icon_override=(None, services.get_active_sim()))
def show_client_connect_on_server(): title = "A client has connected successfully!" notification = UiDialogNotification.TunableFactory().default( services.get_active_sim(), title=lambda **_: LocalizationHelperTuning.get_raw_text(title)) notification.show_dialog(icon_override=(None, services.get_active_sim()))
def show_client_connection_failure(): title = "Connection failed. Perhaps the host and port you specified is incorrect?" notification = UiDialogNotification.TunableFactory().default( services.get_active_sim(), title=lambda **_: LocalizationHelperTuning.get_raw_text(title)) notification.show_dialog(icon_override=(None, services.get_active_sim()))
def on_loading_screen_animation_finished(self): super().on_loading_screen_animation_finished() active_sim = services.get_active_sim() if active_sim is None: return if active_sim.is_on_active_lot(): return camera.focus_on_sim(services.get_active_sim())
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()
def move_sim_inventory_to_household(self): active_sim = services.get_active_sim() active_sim_info = services.active_sim_info() active_sim.inventory_component.push_items_to_household_inventory() self._show_dialog( "Moved all items in {} {}'s inventory to household inventory.". format(active_sim_info.first_name, active_sim_info.last_name))
def _close_business(self, play_sound=True): if not self._is_open: return if play_sound: sound = PlaySound(services.get_active_sim(), self.tuning_data.audio_sting_close.instance) sound.start() self._employee_manager.close_business() self.send_daily_profit_and_cost_update() self._send_business_closed_telemetry() if self._owner_household_id is not None: owner_household = services.household_manager().get(self._owner_household_id) owner_household.bucks_tracker.deactivate_all_temporary_perk_timers_of_type(self.tuning_data.bucks) self.modify_funds(-self._employee_manager.final_daily_wages(), from_item_sold=False) self.on_store_closed() services.get_event_manager().process_event(TestEvent.BusinessClosed) self._distribute_business_open_status(False) if self.business_zone_id == services.current_zone_id(): self.tuning_data.lighting_helper_close.execute_lighting_helper(self) zone_director = services.venue_service().get_zone_director() if zone_director is not None: zone_director.refresh_open_street_director_status() else: self.run_off_lot_simulation() self._last_off_lot_update = None self._is_open = False self.show_summary_dialog(is_from_close=True) self._open_time = None
def run_employee_interaction(self, affordance, target_sim): active_sim = services.get_active_sim() if active_sim is None: return False context = InteractionContext(active_sim, InteractionContext.SOURCE_PIE_MENU, Priority.High) return active_sim.push_super_affordance( affordance, None, context, picked_item_ids=(target_sim.sim_id, ))
def get_street_provider(self): if self.street is None or hasattr(self.street, 'civic_policy'): kwargs = dict() else: kwargs = self.street.get_expected_args() if 'subjects' in kwargs: kwargs['subjects'] = (services.get_active_sim().sim_info, ) if 'picked_zone_ids' in kwargs: kwargs['picked_zone_ids'] = (services.current_zone_id(), ) return self._get_civic_policy_provider(**kwargs)
def print_item_counts(self): active_sim_info = services.active_sim_info() self._show_dialog( "Items in {} {}'s inventory: {}\n" "Items in household inventory: {}".format( active_sim_info.first_name, active_sim_info.last_name, len(services.get_active_sim().inventory_component), len( build_buy.get_object_ids_in_household_inventory( services.active_household_id()))))
def has_user_submitted_entry(self): if self._scores: active_sim = services.get_active_sim() if active_sim is not None: sim_id = active_sim.sim_id for current_score_obj in self._scores: if current_score_obj.sim_id == sim_id: return True return False
def ui_leave_organization(org_id:int, _connection=None): active_sim = services.get_active_sim() if active_sim is None: logger.error('Active Sim is None and cannot be.') return False org_tracker = active_sim.sim_info.organization_tracker if org_tracker is None: logger.error("({})'s organization tracker is None and cannot be.", active_sim.full_name) return False org_tracker.leave_organization(org_id) return org_tracker.get_organization_status(org_id) != OrganizationStatusEnum.ACTIVE
def on_loading_screen_animation_finished(self): household = services.active_household() plex_service = services.get_plex_service() if household is not None and not household.has_home_zone_been_active( ) and plex_service.is_zone_an_apartment( household.home_zone_id, consider_penthouse_an_apartment=False): active_sim = services.get_active_sim() landlord_sim_info = self.get_landlord_sim_info() if active_sim is not None and landlord_sim_info is not None: dialog = LandlordTuning.LANDLORD_FIRST_PLAY_RENT_REMINDER_NOTIFICATION( active_sim) dialog.show_dialog(icon_override=IconInfoData( obj_instance=landlord_sim_info))
def _CreateDialog (self, dialogArguments: dict, *args, **kwargs) -> ui_dialog_picker.UiObjectPicker: dialogOwner = dialogArguments.get("owner") if dialogOwner is None: dialogArguments["owner"] = services.get_active_sim().sim_info dialog = ui_dialog_picker.UiObjectPicker.TunableFactory().default(**dialogArguments) # type: ui_dialog_picker.UiObjectPicker dialogRows = kwargs["dialogRows"] # type: typing.List[DialogRow] for dialogRow in dialogRows: # type: DialogRow dialog.add_row(dialogRow.GenerateRow()) return dialog
def recommend_order_for_table(sim_orders: str, _connection=None): zone_director = get_restaurant_zone_director() if zone_director is None: sims4.commands.output('Current venue is not restaurant', _connection) return False proto = Restaurant_pb2.SimOrders() text_format.Merge(sim_orders, proto) orders = [(order.sim_id, order.recipe_id) for order in proto.sim_orders] sims_in_order = set([ services.object_manager().get(order_sim_id) for order_sim_id in [order[0] for order in orders] ]) for sim in sims_in_order: if sim is None: sims4.commands.output( "Trying to target order for a Sim that isn't on the lot", _connection) return False active_group_order = _get_active_group_order_for_dining_group(sim) if active_group_order: recipe_manager = services.get_instance_manager( sims4.resources.Types.RECIPE) for order in orders: recipe = recipe_manager.get(order[1]) recipes = GroupOrder.get_food_drink_recipe_id_tuple(recipe) active_group_order.add_sim_order( order[0], food_recipe_id=recipes[0], drink_recipe_id=recipes[1], recommendation_state=OrderRecommendationState. RECOMMENDATION_PROPOSAL, order_status=OrderStatus.ORDER_INIT) else: zone_director.order_for_table( orders, send_order=False, recommendation_state=OrderRecommendationState. RECOMMENDATION_PROPOSAL, order_status=OrderStatus.ORDER_INIT) groups = zone_director.get_dining_groups_by_sim(sim) group = groups.pop() group.hold_ordered_cost( proto.meal_cost if has_field(proto, 'meal_cost') else 0) for sim in sims_in_order: zone_director.trigger_recommendation_interaction( services.get_active_sim(), sim) return True
def create_kick_out_situation(kick_out_reason: UniversityHousingKickOutReason, sim_id: int = None, additional_sim_ids: [] = None, university_housing_destination_zone_id: int = 0, _connection=None): if sim_id is None: active_sim = services.get_active_sim() sim_id = active_sim.sim_id guest_list = SituationGuestList(invite_only=True, host_sim_id=sim_id) services.get_zone_situation_manager().create_situation( UniversityHousingTuning.UNIVERSITY_HOUSING_KICK_OUT_SITUATION, guest_list=guest_list, scoring_enabled=False, kick_out_reason=kick_out_reason, additional_sim_ids=additional_sim_ids, university_housing_destination_zone_id= university_housing_destination_zone_id)
def handle_event(self, sim_info, event, resolver): super().handle_event(sim_info, event, resolver) if event == TestEvent.SimActiveLotStatusChanged and not self._tns_popped: sim = sim_info.get_sim_instance() if sim is not None and ( sim.is_on_active_lot() and self.is_sim_in_situation(sim)) and self.sim_has_job( sim, self.neighbor_job_and_default_role_state.job): active_sim = services.get_active_sim() if active_sim is not None: dialog = self._arrival_notification(active_sim) dialog.show_dialog( icon_override=IconInfoData(obj_instance=sim), secondary_icon_override=IconInfoData( obj_instance=active_sim)) self._tns_popped = True services.get_event_manager().unregister_single_event( self, TestEvent.SimActiveLotStatusChanged)
def extend_vacation(self, duration_days, cost=0): extension = clock.interval_in_sim_days(duration_days) self.end_timestamp = self.end_timestamp + extension self.setup_rented_zone_alarms() services.active_household().funds.try_remove( cost, reason=Consts_pb2.FUNDS_MONEY_VACATION, sim=services.get_active_sim()) leader_sim_info = services.active_sim_info() if leader_sim_info not in self: leader_sim_info = self._sim_infos[0] with telemetry_helper.begin_hook(travel_group_telemetry_writer, TELEMETRY_HOOK_TRAVEL_GROUP_EXTEND, sim_info=leader_sim_info) as hook: hook.write_int(TELEMETRY_TRAVEL_GROUP_ID, self.id) hook.write_int(TELEMETRY_TRAVEL_GROUP_ZONE_ID, self.zone_id) hook.write_int(TELEMETRY_TRAVEL_GROUP_SIZE, len(self)) hook.write_int(TELEMETRY_TRAVEL_GROUP_DURATION, int(self.duration_time_span.in_minutes()))
def award_winners(self, show_fallback_dialog=False): valid_sim_won = False winners = self.festival_contest_tuning._winner_selection_method.get_winners( self) sim_info_manager = services.sim_info_manager() for contest_score, award in zip( winners, self.festival_contest_tuning._win_rewards): if not contest_score.sim_id is None: if contest_score.sim_id is 0: pass elif not sim_info_manager.is_sim_id_valid( contest_score.sim_id): pass else: valid_sim_won = True sim = sim_info_manager.get(contest_score.sim_id) resolver = SingleSimResolver(sim) if not self._has_awarded_winners: award.apply_to_resolver(resolver) rank = winners.index(contest_score) if rank >= len( self.festival_contest_tuning._win_notifications): pass else: notification = self.festival_contest_tuning._win_notifications[ rank] dialog = notification( sim, target_sim_id=(contest_score.sim_id), resolver=resolver) dialog.show_dialog() if show_fallback_dialog: if not valid_sim_won: active_sim = services.get_active_sim() resolver = SingleSimResolver(active_sim) dialog = self.festival_contest_tuning._lose_notification( active_sim, target_sim_id=(active_sim.id if active_sim is not None else None), resolver=resolver) dialog.show_dialog() self._has_awarded_winners = True
def perform(self, resolver): roommate_service = services.get_roommate_service() if roommate_service is not None: participant = resolver.get_participant(self.subject) if participant is not None: sim_info = participant.sim_info if self.remove: roommate_service.remove_roommate(sim_info) else: zone_id = services.get_active_sim( ).household.home_zone_id if roommate_service.conform_potential_roommate( sim_info): roommate_service.add_roommate(sim_info, zone_id) else: logger.error( 'Failed to conform {} to be a roommate', sim_info) sim_info.trait_tracker.remove_traits_of_type( traits.traits.TraitType.ROOMMATE)
def create_plumbbob(_connection=None): # Gets the current client connection try: sim_instance = services.get_active_sim() sim_position = sim_instance.position new_plumbob_position = sims4.math.Vector3(float(sim_position.x), float(sim_position.y), float(sim_position.z)) plumbob_object = objects.system.create_object(9716920233444718179) plumbob_object.move_to(translation=new_plumbob_position) # output = sims4.commands.CheatOutput(_connection) # output("Spawned plumbob") # SetAsHead.set_head_object(current_sim, created_obj, "0F97B21B") # output("plumb", dir(created_obj)) plumbob_object.set_parent(sim_instance) except Exception as e: ts4mp_log("plumb", e)
def _open_business(self): self._show_appropriate_open_business_notification() self._clear_state() self._is_open = True self._open_time = services.time_service().sim_now self._employee_manager.open_business() if self._owner_household_id is not None: owner_household = services.household_manager().get(self.owner_household_id) owner_household.bucks_tracker.activate_stored_temporary_perk_timers_of_type(self.tuning_data.bucks) self._distribute_business_open_status(is_open=True, open_time=self._open_time.absolute_ticks()) if self.business_zone_id == services.current_zone_id(): self.tuning_data.lighting_helper_open.execute_lighting_helper(self) zone_director = services.venue_service().get_zone_director() zone_director.set_customers_allowed(True) zone_director.refresh_open_street_director_status() else: self.start_off_lot_simulation_time() sound = PlaySound(services.get_active_sim(), self.tuning_data.audio_sting_open.instance) sound.start() self.send_daily_profit_and_cost_update() self._send_daily_items_sold_update() self._send_review_update_message()
def move_household_inventory_to_sim(self): logger.debug('START OF INVENTORY MIGRATION') active_sim = services.get_active_sim() household = active_sim.household object_ids = build_buy.get_object_ids_in_household_inventory( household.id) moved_object_count = 0 if len(object_ids) > 0: total_cost = 0 for object_id in object_ids: was_success, cost = self._move_item_from_household_to_sims_inventory( object_id, active_sim, household) total_cost += cost if was_success: moved_object_count += 1 # build_buy.remove_object_from_household_inventory() has the side-effect of bumping up # the current household funds as if we are performing a sale, when in reality we merely # want to move the object. # # Fortunately, if we immediately deduct the same value from the household funds, then # the UI doesn't even have a chance to show that anything changed. # if total_cost > 0: self._output( 'Subtracting ${} from household funds to offset sale'. format(total_cost)) if not household.funds.try_remove( total_cost, Consts_pb2.TELEMETRY_OBJECT_SELL, sim=active_sim, require_full_amount=False): self._output('WARN: failed to subtract final amount') active_sim_info = services.active_sim_info() self._show_dialog( "Moved {} items from household into {} {}'s inventory.".format( moved_object_count, active_sim_info.first_name, active_sim_info.last_name)) else: self._show_dialog('No items found in household inventory.')
def push_active_sim_to_buy_business(business_type: BusinessType, _connection=None): output = sims4.commands.Output(_connection) active_sim = services.get_active_sim() if active_sim is None: output('There is no active sim.') return False business_tuning = services.business_service( ).get_business_tuning_data_for_business_type(business_type) if business_tuning is None: output("Couldn't find tuning for business type: {}", business_type) return False context = InteractionContext(active_sim, InteractionContext.SOURCE_SCRIPT, Priority.High) if not active_sim.push_super_affordance( business_tuning.buy_business_lot_affordance, active_sim, context): output('Failed to push the buy affordance on the active sim.') return False with telemetry_helper.begin_hook( business_telemetry_writer, TELEMETRY_HOOK_NEW_GAME_BUSINESS_PURCHASED, household=active_sim.household) as hook: hook.write_enum(TELEMETRY_HOOK_BUSINESS_TYPE, business_type) return True
def pay_for_and_unlock_perk(self, perk): if self.is_perk_unlocked(perk): logger.error( 'Attempting to unlock a Perk {} for owner {} that has already been unlocked.', perk, self._owner) return False if not self.try_modify_bucks(perk.associated_bucks_type, -perk.unlock_cost): logger.error( 'Attempting to unlock a Perk {} for owner {} that they cannot afford.', perk, self._owner) return False self.unlock_perk(perk) if perk.lock_on_purchase is not None: for perk_to_lock in perk.lock_on_purchase: if self.is_perk_unlocked(perk_to_lock): self.lock_perk(perk_to_lock) active_sim = services.get_active_sim() services.get_event_manager().process_event( TestEvent.PerkPurchased, sim_info=active_sim.sim_info, bucks_type=perk.associated_bucks_type, perk=perk) return True
def create_travel_group_and_rent_zone(self, sim_infos, zone_id, played, create_timestamp, end_timestamp, cost=0): setup_alarms = not played travel_group = TravelGroup(played=played, create_timestamp=create_timestamp, end_timestamp=end_timestamp, setup_alarms=setup_alarms) result = self.rent_zone(zone_id, travel_group) if not (result and sim_infos): return False self.add(travel_group) for sim_info in sim_infos: travel_group.add_sim_info(sim_info) if played: leader_sim_info = services.active_sim_info() if leader_sim_info not in sim_infos: leader_sim_info = sim_infos[0] services.active_household().funds.try_remove( cost, reason=Consts_pb2.FUNDS_MONEY_VACATION, sim=services.get_active_sim()) with telemetry_helper.begin_hook(travel_group_telemetry_writer, TELEMETRY_HOOK_TRAVEL_GROUP_START, sim_info=leader_sim_info) as hook: hook.write_int(TELEMETRY_TRAVEL_GROUP_ID, travel_group.id) hook.write_int(TELEMETRY_TRAVEL_GROUP_ZONE_ID, zone_id) hook.write_int(TELEMETRY_TRAVEL_GROUP_SIZE, len(travel_group)) hook.write_int( TELEMETRY_TRAVEL_GROUP_DURATION, int(travel_group.duration_time_span.in_minutes())) return True
def display_dialog(self, notification): active_sim = services.get_active_sim() if active_sim is not None: dialog = self.impatient_notification(active_sim) dialog.show_dialog()
def modify_in_cas(opt_sim:OptionalTargetParam=None, _connection=None): sim = get_optional_target(opt_sim, _connection) if sim is None: sims4.commands.output('No valid target for sims.modify_in_cas.', _connection) return False sims4.commands.client_cheat('sims.exit2cas {} {} {}'.format(sim.id, sim.household_id, services.get_active_sim().id), _connection) return True
def ShowSelectSaveDialog () -> None: gameSaveSlotID = str(services.get_persistence_service().get_save_slot_proto_buff().slot_id) # type: str gameSaveGUID = str(services.get_persistence_service().get_save_slot_proto_guid()) # type: str dialogArguments = { "owner": services.get_active_sim().sim_info, "title": SelectSaveDialogTitle, "text": SelectSaveDialogText.GetCallableLocalizationString(*(gameSaveSlotID, gameSaveGUID)) } dialogRows = list() options = { } # type: typing.Dict[int, str] loadedSaveDirectoryPath = Save.GetLoadedDirectoryPath() # type: typing.Optional[str] loadedSaveDirectoryPathObject = pathlib.Path(Save.GetLoadedDirectoryPath()) if loadedSaveDirectoryPath is not None else None # type: typing.Optional[pathlib.Path] for saveDirectoryName in os.listdir(Paths.SavesPath): # type: str saveDirectoryPath = os.path.join(Paths.SavesPath, saveDirectoryName) # type: str if os.path.isdir(saveDirectoryPath): saveDirectoryPathObject = pathlib.Path(saveDirectoryPath) # type: pathlib.Path currentOptionID = 50000 + len(options) options[currentOptionID] = saveDirectoryPath saveDirectoryMetaData = Save.GetSaveMetaData(saveDirectoryPath) # type: typing.Optional[Save.ModSaveMetaData] rowDescriptionTokens = (SelectSaveDialogDescriptionMatchUnknown.GetLocalizationString(),) if saveDirectoryMetaData is not None: saveDirectoryMatchType = saveDirectoryMetaData.MatchesGameSave() # type: Save.ModSaveMatchTypes if saveDirectoryMatchType in Save.ModSaveMatchTypes.Match: rowDescriptionTokens = (SelectSaveDialogDescriptionMatchMatches.GetLocalizationString(),) elif saveDirectoryMatchType in Save.ModSaveMatchTypes.MismatchedGUID: rowDescriptionTokens = (SelectSaveDialogDescriptionMatchMismatchGUID.GetLocalizationString(),) elif saveDirectoryMatchType in Save.ModSaveMatchTypes.MismatchedGameTick: rowDescriptionTokens = (SelectSaveDialogDescriptionMatchMismatchGameTick.GetLocalizationString(),) if loadedSaveDirectoryPathObject is not None: if loadedSaveDirectoryPathObject == saveDirectoryPathObject: rowDescription = SelectSaveDialogDescriptionCurrentlyLoaded.GetLocalizationString(*rowDescriptionTokens) else: rowDescription = SelectSaveDialogDescriptionNormal.GetLocalizationString(*rowDescriptionTokens) else: rowDescription = SelectSaveDialogDescriptionNormal.GetLocalizationString(*rowDescriptionTokens) if saveDirectoryMetaData is None: rowNameTokens = (saveDirectoryName,) else: rowNameTokens = (saveDirectoryName + " (" + saveDirectoryMetaData.Name + ")",) dialogRows.append(ui_dialog_picker.ObjectPickerRow( option_id = currentOptionID, name = Language.CreateLocalizationString(*rowNameTokens), row_description = rowDescription)) def DialogCallback (dialogReference: ui_dialog_picker.UiObjectPicker) -> None: try: if dialogReference.response == ui_dialog.ButtonType.DIALOG_RESPONSE_CANCEL: return resultRows = dialogReference.picked_results # type: typing.Tuple[int] if len(resultRows) == 0: return selectedSaveDirectory = options.get(resultRows[0]) # type: typing.Optional[str] if selectedSaveDirectory is None: return Save.Load(services.get_persistence_service().get_save_slot_proto_buff().slot_id, selectedSaveDirectory, changingSave = True) except Exception as e: Debug.Log("Failed to run the callback for the select save dialog.", This.Mod.Namespace, Debug.LogLevels.Exception, group = This.Mod.Namespace, owner = __name__, exception = e) Dialogs.ShowObjectPickerDialog(DialogCallback, dialogRows, **dialogArguments)