using System; using System.Collections.Generic; using StardewModdingAPI.Framework.Networking; using StardewValley; namespace StardewModdingAPI.Framework.ModHelpers { /// Provides multiplayer utilities. internal class MultiplayerHelper : BaseHelper, IMultiplayerHelper { /********* ** Fields *********/ /// SMAPI's core multiplayer utility. private readonly SMultiplayer Multiplayer; /********* ** Public methods *********/ /// Construct an instance. /// The unique ID of the relevant mod. /// SMAPI's core multiplayer utility. public MultiplayerHelper(string modID, SMultiplayer multiplayer) : base(modID) { this.Multiplayer = multiplayer; } /// Get a new multiplayer ID. public long GetNewID() { return this.Multiplayer.getNewID(); } /// Get the locations which are being actively synced from the host. public IEnumerable GetActiveLocations() { return this.Multiplayer.activeLocations(); } /// Get a connected player. /// The player's unique ID. /// Returns the connected player, or null if no such player is connected. public IMultiplayerPeer GetConnectedPlayer(long id) { return this.Multiplayer.Peers.TryGetValue(id, out MultiplayerPeer peer) ? peer : null; } /// Get all connected players. public IEnumerable GetConnectedPlayers() { return this.Multiplayer.Peers.Values; } /// Send a message to mods installed by connected players. /// The data type. This can be a class with a default constructor, or a value type. /// The data to send over the network. /// A message type which receiving mods can use to decide whether it's the one they want to handle, like SetPlayerLocation. This doesn't need to be globally unique, since mods should check the originating mod ID. /// The mod IDs which should receive the message on the destination computers, or null for all mods. Specifying mod IDs is recommended to improve performance, unless it's a general-purpose broadcast. /// The values for the players who should receive the message, or null for all players. If you don't need to broadcast to all players, specifying player IDs is recommended to reduce latency. /// The or is null. public void SendMessage(TMessage message, string messageType, string[] modIDs = null, long[] playerIDs = null) { this.Multiplayer.BroadcastModMessage( message: message, messageType: messageType, fromModID: this.ModID, toModIDs: modIDs, toPlayerIDs: playerIDs ); } } }