1
0

PickRandomSystem.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Linq;
  2. using Content.Server.Storage.Components;
  3. using Content.Shared.Database;
  4. using Content.Shared.Hands.EntitySystems;
  5. using Content.Shared.Storage;
  6. using Content.Shared.Verbs;
  7. using Content.Shared.Whitelist;
  8. using Robust.Shared.Containers;
  9. using Robust.Shared.Random;
  10. namespace Content.Server.Storage.EntitySystems;
  11. // TODO: move this to shared for verb prediction if/when storage is in shared
  12. public sealed class PickRandomSystem : EntitySystem
  13. {
  14. [Dependency] private readonly SharedContainerSystem _container = default!;
  15. [Dependency] private readonly SharedHandsSystem _hands = default!;
  16. [Dependency] private readonly IRobustRandom _random = default!;
  17. [Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
  18. public override void Initialize()
  19. {
  20. base.Initialize();
  21. SubscribeLocalEvent<PickRandomComponent, GetVerbsEvent<AlternativeVerb>>(OnGetAlternativeVerbs);
  22. }
  23. private void OnGetAlternativeVerbs(EntityUid uid, PickRandomComponent comp, GetVerbsEvent<AlternativeVerb> args)
  24. {
  25. if (!args.CanAccess || !args.CanInteract || !TryComp<StorageComponent>(uid, out var storage))
  26. return;
  27. var user = args.User;
  28. var enabled = storage.Container.ContainedEntities.Any(item => _whitelistSystem.IsWhitelistPassOrNull(comp.Whitelist, item));
  29. // alt-click / alt-z to pick an item
  30. args.Verbs.Add(new AlternativeVerb
  31. {
  32. Act = () =>
  33. {
  34. TryPick(uid, comp, storage, user);
  35. },
  36. Impact = LogImpact.Low,
  37. Text = Loc.GetString(comp.VerbText),
  38. Disabled = !enabled,
  39. Message = enabled ? null : Loc.GetString(comp.EmptyText, ("storage", uid))
  40. });
  41. }
  42. private void TryPick(EntityUid uid, PickRandomComponent comp, StorageComponent storage, EntityUid user)
  43. {
  44. var entities = storage.Container.ContainedEntities.Where(item => _whitelistSystem.IsWhitelistPassOrNull(comp.Whitelist, item)).ToArray();
  45. if (!entities.Any())
  46. return;
  47. var picked = _random.Pick(entities);
  48. // if it fails to go into a hand of the user, will be on the storage
  49. _container.AttachParentToContainerOrGrid((picked, Transform(picked)));
  50. // TODO: try to put in hands, failing that put it on the storage
  51. _hands.TryPickupAnyHand(user, picked);
  52. }
  53. }