ArcadeSystem.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Linq;
  2. using Content.Server.UserInterface;
  3. using Content.Shared.Arcade;
  4. using Robust.Shared.Utility;
  5. using Robust.Server.GameObjects;
  6. using Robust.Server.Player;
  7. namespace Content.Server.Arcade
  8. {
  9. // ReSharper disable once ClassNeverInstantiated.Global
  10. public sealed partial class ArcadeSystem : EntitySystem
  11. {
  12. private readonly List<BlockGameMessages.HighScoreEntry> _roundHighscores = new();
  13. private readonly List<BlockGameMessages.HighScoreEntry> _globalHighscores = new();
  14. public override void Initialize()
  15. {
  16. base.Initialize();
  17. }
  18. public HighScorePlacement RegisterHighScore(string name, int score)
  19. {
  20. var entry = new BlockGameMessages.HighScoreEntry(name, score);
  21. return new HighScorePlacement(TryInsertIntoList(_roundHighscores, entry), TryInsertIntoList(_globalHighscores, entry));
  22. }
  23. public List<BlockGameMessages.HighScoreEntry> GetLocalHighscores() => GetSortedHighscores(_roundHighscores);
  24. public List<BlockGameMessages.HighScoreEntry> GetGlobalHighscores() => GetSortedHighscores(_globalHighscores);
  25. private List<BlockGameMessages.HighScoreEntry> GetSortedHighscores(List<BlockGameMessages.HighScoreEntry> highScoreEntries)
  26. {
  27. var result = highScoreEntries.ShallowClone();
  28. result.Sort((p1, p2) => p2.Score.CompareTo(p1.Score));
  29. return result;
  30. }
  31. private int? TryInsertIntoList(List<BlockGameMessages.HighScoreEntry> highScoreEntries, BlockGameMessages.HighScoreEntry entry)
  32. {
  33. if (highScoreEntries.Count < 5)
  34. {
  35. highScoreEntries.Add(entry);
  36. return GetPlacement(highScoreEntries, entry);
  37. }
  38. if (highScoreEntries.Min(e => e.Score) >= entry.Score) return null;
  39. var lowestHighscore = highScoreEntries.Min();
  40. if (lowestHighscore == null) return null;
  41. highScoreEntries.Remove(lowestHighscore);
  42. highScoreEntries.Add(entry);
  43. return GetPlacement(highScoreEntries, entry);
  44. }
  45. private int? GetPlacement(List<BlockGameMessages.HighScoreEntry> highScoreEntries, BlockGameMessages.HighScoreEntry entry)
  46. {
  47. int? placement = null;
  48. if (highScoreEntries.Contains(entry))
  49. {
  50. highScoreEntries.Sort((p1,p2) => p2.Score.CompareTo(p1.Score));
  51. placement = 1 + highScoreEntries.IndexOf(entry);
  52. }
  53. return placement;
  54. }
  55. public readonly struct HighScorePlacement
  56. {
  57. public readonly int? GlobalPlacement;
  58. public readonly int? LocalPlacement;
  59. public HighScorePlacement(int? globalPlacement, int? localPlacement)
  60. {
  61. GlobalPlacement = globalPlacement;
  62. LocalPlacement = localPlacement;
  63. }
  64. }
  65. }
  66. }