/// <summary> /// Removes the specified Realm from the game world /// </summary> /// <param name="realm"></param> public void RemoveRealm(IRealm realm) { if (Realms.Contains(realm)) { Realms.Remove(realm); } }
/// <summary>Entity modified.</summary> /// <param name="realm">Realm.</param> /// <param name="entity">Entity.</param> public override void ModifyEntity(IRealm realm, object entity) { lock (_modified) { if (!_modified.Any(x => x.Key == entity && x.Value == ModifiedEntityState.Added)) _modified[entity] = ModifiedEntityState.Modified; } }
/// <summary> /// Destroys the Room and /// </summary> public override void Destroy() { Doorways.Clear(); Doorways = null; List <IPlayer> playerCollection = new List <IPlayer>(); foreach (IMob mob in Occupants) { if (mob is IPlayer) { playerCollection.Add((IPlayer)mob); } } this.BroadcastMessage("Room is being destroyed! You will be teleported to a new location.", playerCollection.ToList()); // Trace back up through the environment path to get the World IWorld world = Zone.Realm.World; //Get the initial Room location, and split it up into an array so we can parse it string[] roomPath = EngineSettings.Default.InitialRoom.Split('>'); // Make sure we have three entries, Realm, Zone and Room if (roomPath.Length != 3) { return; } // Get the Realm IRealm realm = world.GetRealm(roomPath[0]); if (realm == null) { return; } // Get our Zone IZone zone = realm.GetZone(roomPath[1]); if (zone == null) { return; } // Get the initial Room IRoom room = zone.GetRoom(roomPath[2]); if (room == null) { return; } // Loop through each player in this Room and move them to the initial Room. foreach (IPlayer player in Occupants) { player.Move(room); player.SendMessage("You have been moved to " + room.Name); } }
public Weather(IRealm realm, ISendMessageEvent sendMessageEvent) { _realm = realm.RealmReversed; _sendMessageEvent = sendMessageEvent; _territoryList = LoadZones(); }
/// <summary>Realm has been started.</summary> /// <param name="realm">Realm.</param> public override void Start(IRealm realm) { // Creates decorations realm.AddEntity(new Decoration { X = 64 * 3, Y = 64 * 3 }); realm.AddEntity(new Decoration { X = 64 * 6, Y = 64 * 3 }); // Creates ground realm.AddEntity(Ground.CreateBlock(64 * 1, 64 * 2)); realm.AddEntity(Ground.CreateBlock(64 * 0, 64 * 10)); realm.AddEntity(Ground.CreateBlock(64 * 1, 64 * 1)); realm.AddEntity(Ground.CreateBlock(64 * 1, 64 * 5)); realm.AddEntity(Ground.CreateBlock(64 * 2, 64 * 5)); realm.AddEntity(Ground.CreateBlock(64 * 3, 64 * 5)); realm.AddEntity(Ground.CreateBlock(64 * 3, 64 * 6)); realm.AddEntity(Ground.CreateBlock(64 * 4, 64 * 6)); realm.AddEntity(Ground.CreateBlock(64 * 5, 64 * 6)); realm.AddEntity(Ground.CreateBlock(64 * 6, 64 * 8)); realm.AddEntity(Ground.CreateBlock(64 * 7, 64 * 8)); realm.AddEntity(Ground.CreateBlock(64 * 8, 64 * 8)); realm.AddEntity(Ground.CreateBlock(64 * 6, 64 * 5)); realm.AddEntity(Ground.CreateBlock(64 * 0, 64 * 1)); for (var i = 0; i < 20; ++i) { realm.AddEntity(Ground.CreateBlock(64 * i, 64 * 9)); realm.AddEntity(Ground.CreateBlock(64 * 12, 64 * i)); } realm.AddEntity(new Ball { X = 64 * 3, Y = 64 * 3 }); realm.AddEntity(new Gate { X = 64 * 6, Y = 64 * 4 }); /*_realm.AddEntity(new Ground(new[] { new Point(10, 100), new Point(290, 250), new Point(420, 450), new Point(580, 350), new Point(620, 750), new Point(30, 790) }));*/ }
/// <summary>User input.</summary> /// <param name="realm">Realm.</param> /// <param name="user">User.</param> /// <param name="state">Input state.</param> public override void Input(IRealm realm, User user, InputState state) { var player = (Player)user["player"]; player.VectorX = (state.Get<bool>("right") ? 1 : state.Get<bool>("left") ? -1 : 0) * 20; player.VectorY = (state.Get<bool>("up") ? 1 : state.Get<bool>("down") ? -1 : 0) * 80; player.AimAngle = state.Get<float>("aimAngle"); }
static void Main(string[] args) { try { _realm = new AwsRealm(); _queueProvider = _realm.QueueProvider; const string queueId = "cloudmorph-testqueue"; try { var queue = _queueProvider.GetQueueById(queueId); Console.WriteLine("Queue exists."); return; } catch { } bool bResult = _queueProvider.CreateQueue(queueId); if (bResult) Console.WriteLine("The queue {0} was successfully created", queueId); } catch (Exception e) { Console.WriteLine(e); } }
public override void Update(IRealm realm, double delta) { foreach (var bullet in realm.Entities.OfType<BulletViewModel>()) { bullet.X += (bullet.NewX - bullet.X) * .5f; bullet.Y += (bullet.NewY - bullet.Y) * .5f; realm.ModifyEntity(bullet); } }
public override void Update(IRealm realm, double delta) { foreach (var ball in realm.Entities.OfType<BallViewModel>()) { ball.X += (ball.NewX - ball.X) * .5; ball.Y += (ball.NewY - ball.Y) * .5; realm.ModifyEntity(ball); } }
private void comRealms_SelectedIndexChanged(object sender, EventArgs e) { if (comRealms.SelectedIndex == -1) { return; } IRealm realm = Editor.Game.World.GetRealm(comRealms.SelectedItem.ToString()); string[] values = null; bool validPath = false; if (!String.IsNullOrEmpty(EngineSettings.Default.InitialRoom)) { values = EngineSettings.Default.InitialRoom.Split('>'); if (values.Length == 3) { validPath = true; } } if (realm == null) { MessageBox.Show("There was an error retreiving the specified realm.", this.Text); return; } else { //Must be set prior to setting the index of the combo box SelectedRealm = realm; } IZone[] zones = realm.GetZones(); if (zones == null) { return; } foreach (IZone zone in zones) { comZones.Items.Add(zone.Name); if (validPath) { if (values[1] == zone.Name) { comZones.SelectedItem = zone.Name; } } } if (comZones.Items.Count > 0) { comZones.SelectedIndex = 0; } }
private void realmsBtnAddRealm_Click(object sender, EventArgs e) { //We need to make sure we never have a duplicate name. int value = 1; string newName = "New Realm" + value; //New Realm1 //Once we have a Realm with a unique name, this will become true bool validName = false; //Loop until we have a valid Realm name that is not duplicated. while (!validName) { //In the event this is the first Realm. //Prevents infinit loop //Since we have zero Realms that exists, of course the first one will be valid. if (Editor.Game.World.GetRealms().Length == 0) { validName = true; } //Loop through each Realm and check it's name foreach (var r in Editor.Game.World.GetRealms()) { //We found a match, so it's considered a duplicate. if (r.Name == newName) { //Increase our number value++; //Update our name newName = "New Realm" + value; } else { //Otherwise we are good to go validName = true; } } } //Grab a new instance of the default IRealm specified in the engine settings IRealm realm = (IRealm)ScriptFactory.GetScript(MudDesigner.Engine.Properties.EngineSettings.Default.RealmScript, null); if (realm == null) { //In the event the scripts didn't compile or are missing MessageBox.Show("There are currently no Realm scripts that exist. Please create a script that inherits from MudDesigner.Engine.Environments.BaseRealm", "Mud Designer Editor : Realms", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //Set the name we built realm.Name = newName; //Add it to the World Editor.Game.World.AddRealm(realm); //Add it and select it on our Realm List Collection realmsLstExistingRealms.Items.Add(realm.Name); realmsLstExistingRealms.SelectedItem = realm.Name; }
/// <summary> /// Initializes a new instance of the <see cref="MudZone"/> class. /// </summary> public MudZone(IRoomFactory roomFactory, IRealm owner) { this.WeatherUpdateFrequency = 15; this.rooms = new List <IRoom>(); this.weatherStates = new List <IWeatherState>(); this.Owner = owner; this.roomFactory = roomFactory; }
/// <summary> /// Initializes a new instance of the <see cref="MudZone"/> class. /// </summary> public MudZone(IRoomFactory roomFactory, IRealm owner) { this.WeatherUpdateFrequency = 15; this.rooms = new List<IRoom>(); this.weatherStates = new List<IWeatherState>(); this.Owner = owner; this.roomFactory = roomFactory; }
public void Begin(IRealm owner) { var proj = new Projectile(); proj.SetDefaultsDirect((int)BorderProjID); projSize = proj.Size; this.owner = owner; }
/// <summary>Entity removed from realm.</summary> /// <param name="realm">Realm.</param> /// <param name="entity">Entity.</param> public override void RemoveEntity(IRealm realm, object entity) { /*var exist = _list.FirstOrDefault(x => x.Key == entity); if (exist.Key != null) { if (exist.Value == EntityState.Modified) exist.Value = EntityState.Removed; if (exist.Value == EntityState.Added) _list.Remove(exist); } else _list.Add(new KeyValuePair<object, EntityState>(entity, EntityState.Removed));*/ _list.Add(new KeyValuePair<object, EntityState>(entity, EntityState.Removed)); }
/// <summary>New user joined to the game as observer.</summary> /// <param name="realm">Realm.</param> /// <param name="user">User.</param> /// <returns>Aceept user to the game?</returns> public override bool Enter(IRealm realm, User user) { user["player"] = new Player { X = 64 * 3, Name = "Player_" + DateTime.Now.Millisecond, ClientSessionId = user.Session }; realm.AddEntity(user["player"]); return true; }
public SocketManager(IRealm realmInterface) { sockets = new List <TCPSocket>(); packetisers = new List <Packetiser>(); codecs = new List <Codec>(); listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 54540); listener.Start(); portID_Counter = 0; this.realm = realmInterface; }
private void roomsBtnDeleteRoom_Click(object sender, EventArgs e) { //Make sure all of the required UI elements are selected if (roomsLstExistingRooms.SelectedIndex == -1) { MessageBox.Show("You must select a Room first.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (roomsComRealms.SelectedIndex == -1 || roomsComZones.SelectedIndex == -1) { MessageBox.Show("You must select both a Realm and a Zone first.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Grab a reference to the Realm. IRealm realm = Editor.Game.World.GetRealm(roomsComRealms.SelectedItem.ToString()); if (realm == null) { MessageBox.Show("Failed to locate the selected Realm within the system for an unknown reason!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Get a reference to the zone the selected Room belongs to. IZone zone = realm.GetZone(roomsComZones.SelectedItem.ToString()); if (zone == null) { MessageBox.Show("Failed to locate the selected Zone within the system for an unknown reason!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Get a reference to the room that the user wants to delete. IRoom room = zone.GetRoom(roomsLstExistingRooms.SelectedItem.ToString()); if (room == null) { MessageBox.Show("Failed to locate the selected Room within the system for an unknown reason!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Remove the room from our list collection if (Editor.CurrentRoom.ToString() == string.Format("{0}>{1}>{2}", roomsComRealms.SelectedItem.ToString(), roomsComZones.SelectedItem.ToString(), room.Name)) { Editor.CurrentRoom = null; } roomsLstExistingRooms.Items.Remove(room.Name); //Remove the room from the Zone zone.RemoveRoom(room); //Null the reference. room = null; RefreshRoomLabels(Editor.CurrentRealm, Editor.CurrentZone, Editor.CurrentRoom); }
private async Task HandleMessageAsync(IClient client, string text, IRealm realm, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(text)) { return; } var message = JsonConvert.DeserializeObject <Message>(text); await realm.HandleMessageAsync(client, message, cancellationToken); }
public override void Update(IRealm realm, double delta) { var balls = realm.Entities.OfType<Ball>(); var gates = realm.Entities.OfType<Gate>(); foreach (var gate in gates) { foreach (var ball in balls) { if (ball.X > gate.X && ball.X < gate.X + 64 && ball.Y > gate.Y && ball.Y < gate.Y + 64) { gate.Score += 1; } } } }
/// <summary> /// Initializes a new instance of the <see cref="BaseZone"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="realm">The realm.</param> public BaseZone(string name, IRealm realm) { Rooms = new List <IRoom>(); if (realm != null) { Realm = realm; } Name = name; Enabled = true; }
/// <summary>Entity added to realm.</summary> /// <param name="realm">Realm.</param> /// <param name="entity">Entity.</param> public override void AddEntity(IRealm realm, object entity) { Body body = null; if (entity.GetType() == typeof(Decoration)) return; if (entity.GetType() == typeof(Gate)) return; if (entity.GetType() == typeof(Ball)) body = new BallPhysicsBodyFactory().Create(_world, (Ball)entity); if (entity.GetType() == typeof(Player)) body = new PlayerPhysicsBodyFactory().Create(_world, (Player)entity); if (entity.GetType() == typeof(Ground)) body = new GroundPhysicsBodyFactory().Create(_world, (Ground)entity); if (entity.GetType() == typeof(Bullet)) body = new BulletPhysicsBodyFactory(realm).Create(_world, (Bullet)entity); if (body == null) throw new InvalidOperationException(string.Format("Can not create physics body for {0}", entity.GetType())); _entities.Add(entity, body); }
/// <summary> /// Initializes a new instance of the <see cref="BaseZone"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="realm">The realm.</param> public BaseZone(string name, IRealm realm) { Rooms = new List<IRoom>(); if (realm != null) { Realm = realm; } Name = name; Enabled = true; }
public async Task World_can_create_a_realm() { // Arrange IRealmFactory factory = Mock.Of <IRealmFactory>( mock => mock.CreateRealm(It.IsAny <string>(), It.IsAny <IWorld>()) == Task.FromResult(Mock.Of <IRealm>())); var world = new MudWorld(factory); var realmName = "Test Realm"; // Act IRealm realm = await world.CreateRealm(realmName); // Assert Assert.IsNotNull(realm); }
/// <summary> /// Creates a new uninitialized zone. /// Each of the rooms added will be initialized prior to adding it to the zone. /// </summary> /// <param name="name">The name of the zone.</param> /// <param name="owner">The realm that owns this zone.</param> /// <param name="weatherStates">The weather states to be made available in the zone.</param> /// <param name="weatherUpdateFrequency">The frequency to which the weather should be updated.</param> /// <param name="rooms">A collection of rooms that will be initialized and added to the zone.</param> /// <returns> /// Returns an uninitialized zone instance /// </returns> public async Task<IZone> CreateZone(string name, IRealm owner, IEnumerable<IWeatherState> weatherStates, int weatherUpdateFrequency, IEnumerable<IRoom> rooms) { MudZone zone = weatherStates.Count() > 0 ? zone = new MudZone(this.roomFactory, owner, weatherStates) : zone = new MudZone(this.roomFactory, owner); zone.SetName(name); zone.WeatherUpdateFrequency = weatherUpdateFrequency; if (rooms.Count() > 0) { await zone.AddRoomsToZone(rooms); } return zone; }
/// <summary>User input.</summary> /// <param name="realm">Realm.</param> /// <param name="user">User.</param> /// <param name="state">Keys.</param> public override void Input(IRealm realm, User user, InputState state) { var player = (Player)user["player"]; var aimAngle = state.Get<float>("aimAngle"); var kickBall = state.Get<bool>("kick"); var aimAngleRad = aimAngle / 180.0f * Math.PI; // if (kickBall) { foreach (var ball in realm.Entities.OfType<Ball>()) { ball.VectorX = (float)Math.Cos(aimAngleRad) * 25000; ball.VectorY = (float)Math.Sin(aimAngleRad) * 25000; } } }
/// <summary> /// Creates a new uninitialized zone. /// Each of the rooms added will be initialized prior to adding it to the zone. /// </summary> /// <param name="name">The name of the zone.</param> /// <param name="owner">The realm that owns this zone.</param> /// <param name="weatherStates">The weather states to be made available in the zone.</param> /// <param name="weatherUpdateFrequency">The frequency to which the weather should be updated.</param> /// <param name="rooms">A collection of rooms that will be initialized and added to the zone.</param> /// <returns> /// Returns an uninitialized zone instance /// </returns> public async Task <IZone> CreateZone(string name, IRealm owner, IEnumerable <IWeatherState> weatherStates, int weatherUpdateFrequency, IEnumerable <IRoom> rooms) { MudZone zone = weatherStates.Count() > 0 ? zone = new MudZone(this.roomFactory, owner, weatherStates) : zone = new MudZone(this.roomFactory, owner); zone.SetName(name); zone.WeatherUpdateFrequency = weatherUpdateFrequency; if (rooms.Count() > 0) { await zone.AddRoomsToZone(rooms); } return(zone); }
/// <summary> /// Removes the given realm from this world instance, deleting the realm in the process. /// If it must be reused, you may clone the realm and add the clone to another world. /// </summary> /// <param name="realm">The realm to remove.</param> /// <returns>Returns an awaitable Task</returns> public Task RemoveRealmFromWorld(IRealm realm) { if (realm == null) { return(Task.FromResult(0)); } if (!this.realms.Contains(realm)) { return(Task.FromResult(0)); } this.realms.Remove(realm); return(realm.Delete()); }
private void roomsComRealms_SelectedIndexChanged(object sender, EventArgs e) { if (roomsComRealms.SelectedIndex == -1) { return; } IRealm realm = null; //If CurrentRealm is not null and we have the CurrentRealm selected, set that as our reference. //Saves us from having to loop through all of the other realms via World.GetRealm() if (Editor.CurrentRealm != null && roomsComRealms.SelectedItem.ToString() == Editor.CurrentRealm.Name) { realm = Editor.CurrentRealm; } else { //CurrentRealm is not the Realm we have selected, so lets find it. realm = (IRealm)Editor.Game.World.GetRealm(roomsComRealms.SelectedItem.ToString()); } //In the event that GetRealm can't find the Realm selected for some reason, bail. if (realm == null) { return; } //Loop through each Zone in the selected Realm and build the combo box collection. foreach (IZone zone in realm.Zones) { roomsComZones.Items.Add(zone.Name); } //If the CurrentRealm matches the currently selected realm, then check if the CurrentZone is null. //If not, then automatically select the current Zone out of the collection. If CurrentZone is null //or does not exist within CurrentRealm, select the first item in the collection if (Editor.CurrentRealm != null && Editor.CurrentRealm.Name == roomsComRealms.SelectedItem.ToString()) { if (Editor.CurrentZone != null && roomsComZones.Items.Contains(Editor.CurrentZone.Name)) { roomsComZones.SelectedItem = Editor.CurrentZone.Name; } } else if (roomsComZones.Items.Count > 0) { roomsComZones.SelectedIndex = 0; } }
/// <summary> /// Adds the supplied Realm to the game world. /// </summary> /// <param name="realm">The Realm you want to add to the world</param> /// <param name="forceOverwrite">If true, it will overwrite the Realm if it already exists within the World</param> public void AddRealm(IRealm realm, bool forceOverwrite = false) { if (realm == null) return; if (forceOverwrite) { if (Realms.Contains(realm)) { Realms.Remove(realm); } } realm.World = this; Realms.Add(realm); }
public async Task Adding_realm_to_world_without_a_name_throws_exception() { // Arrange IRealmFactory factory = Mock.Of <IRealmFactory>( mock => mock.CreateRealm(It.IsAny <string>(), It.IsAny <IWorld>()) == Task.FromResult(Mock.Of <IRealm>())); var world = new MudWorld(factory); var realmName = "Test Realm"; IRealm realm = await world.CreateRealm(realmName); // Act await world.AddRealmToWorld(realm); // Assert Assert.Fail(); }
private void roomsComZones_SelectedIndexChanged(object sender, EventArgs e) { if (roomsComZones.SelectedIndex == -1) { return; } //Since we are changing Zones, clear out our Rooms list. roomsLstExistingRooms.Items.Clear(); //Get the current Realm that we have selected. IRealm realm = (IRealm)Editor.Game.World.GetRealm(roomsComRealms.SelectedItem.ToString()); //If the realm doesn't exist, abort. if (realm == null) { return; } //Get the current Zone we have selected IZone zone = realm.GetZone(roomsComZones.SelectedItem.ToString()); if (zone == null) { return; } //Loop through each Room in the current Zone and place it in our list collection foreach (IRoom room in zone.Rooms) { roomsLstExistingRooms.Items.Add(room.Name); } //Check if EngineEditor.CurrentRoom is one of the Rooms within our List. If so, select it. if (Editor.CurrentRealm == null || Editor.CurrentZone == null || Editor.CurrentRoom == null) { return; //Bail, we don't need to go any further. } if (Editor.CurrentRealm.Name == roomsComRealms.SelectedItem.ToString() && Editor.CurrentZone.Name == roomsComZones.SelectedItem.ToString()) { if (roomsLstExistingRooms.Items.Contains(Editor.CurrentRoom.Name)) { roomsLstExistingRooms.SelectedItem = Editor.CurrentRoom.Name; } } }
private async Task PruneExpiredMessagesAsync(IRealm realm, CancellationToken stoppingToken) { var clientIds = realm.GetClientIdsWithQueue(); var now = DateTime.UtcNow; var maxDiff = TimeSpan.FromSeconds(10); var seenMap = new Dictionary <string, bool>(); foreach (var clientId in clientIds) { var messageQueue = realm.GetMessageQueueById(clientId); if (messageQueue == null) { continue; } var lastReadDiff = now - messageQueue.GetReadTimestamp(); if (lastReadDiff < maxDiff) { continue; } var messages = messageQueue.GetAll(); foreach (var message in messages) { var seenKey = $"{message.Source}_{message.Destination};"; if (!seenMap.TryGetValue(seenKey, out var seen) || !seen) { var sourceClient = realm.GetClient(message.Source); await realm.HandleMessageAsync(sourceClient, Message.Create(MessageType.Expire, string.Empty), stoppingToken); seenMap[seenKey] = true; } } realm.ClearMessageQueue(clientId); } _logger.LogInformation($"Pruned expired messages for {seenMap.Keys.Count} peers."); }
public async Task World_can_add_new_realm() { // Arrange IRealmFactory factory = Mock.Of <IRealmFactory>( mock => mock.CreateRealm(It.IsAny <string>(), It.IsAny <IWorld>()) == Task.FromResult( Mock.Of <IRealm>(r => r.Name == "Unit Test"))); var world = new MudWorld(factory); var realmName = "Test Realm"; IRealm realm = await world.CreateRealm(realmName); // Act await world.AddRealmToWorld(realm); // Assert Assert.AreEqual(1, world.GetRealmsInWorld().Count()); }
public async Task Adding_realm_sets_its_enabled_flag() { // Arrange IRealmFactory factory = Mock.Of <IRealmFactory>(mock => mock.CreateRealm(It.IsAny <string>(), It.IsAny <IWorld>()) == Task.FromResult( Mock.Of <IRealm>(r => r.Name == "Unit Test" && r.IsEnabled == true))); var world = new MudWorld(factory); var realmName = "Test Realm"; IRealm realm = await world.CreateRealm(realmName); // Act await world.AddRealmToWorld(realm); // Assert Assert.IsTrue(realm.IsEnabled); }
/// <summary> /// Initializes and then adds the given realm to this world instance. /// </summary> /// <param name="realm">The realm to add.</param> /// <returns>Returns an awaitable Task</returns> /// <exception cref="MudDesigner.MudEngine.Environment.InvalidRealmException">The realm name can not be null or blank.</exception> public async Task AddRealmToWorld(IRealm realm) { if (this.realms.Contains(realm)) { return; } if (string.IsNullOrEmpty(realm.Name)) { throw new InvalidRealmException(realm, "The realm name can not be null or blank."); } realm.Owner = this; await realm.Initialize(); this.realms.Add(realm); }
/// <summary> /// Adds the supplied Realm to the game world. /// </summary> /// <param name="realm">The Realm you want to add to the world</param> /// <param name="forceOverwrite">If true, it will overwrite the Realm if it already exists within the World</param> public void AddRealm(IRealm realm, bool forceOverwrite = false) { if (realm == null) { return; } if (forceOverwrite) { if (Realms.Contains(realm)) { Realms.Remove(realm); } } realm.World = this; Realms.Add(realm); }
public override void Update(IRealm realm, double delta) { foreach (var player in realm.Entities.OfType<PlayerViewModel>()) { player.AimAngle += (player.NewAimAngle - player.AimAngle) * .3; player.X += (player.NewX - player.X) * .3; player.Y += (player.NewY - player.Y) * .3; if ((player.NewX - player.X) > 1) player.State = "RunRight"; else if ((player.NewX - player.X) < -1) player.State = "RunLeft"; else player.State = "Stay"; //player.X = player.NewX; //player.Y = player.NewY; realm.ModifyEntity(player); } }
/// <summary>User input.</summary> /// <param name="realm">Realm.</param> /// <param name="user">User.</param> /// <param name="state">Keys.</param> public override void Input(IRealm realm, User user, InputState state) { var player = (Player)user["player"]; var aimAngle = state.Get<float>("aimAngle"); var fire = state.Get<bool>("fire"); var aimAngleRad = aimAngle / 180.0f * Math.PI; if (fire) { var vectorX = (float)Math.Cos(aimAngleRad); var vectorY = (float)Math.Sin(aimAngleRad); var bullet = new Bullet { X = player.X + vectorX * 25, Y = player.Y + vectorY * 25, VectorX = vectorX * 50, VectorY = vectorY * 50 }; realm.AddEntity(bullet); } }
/// <summary>Update realm.</summary> /// <param name="realm">Realm.</param> /// <param name="delta">Time passed since last update.</param> public override void Update(IRealm realm, double delta) { foreach (var entity in realm.Entities.OfType<Player>()) { realm.ModifyEntity(entity); } foreach (var entity in realm.Entities.OfType<Ball>()) { realm.ModifyEntity(entity); } foreach (var entity in realm.Entities.OfType<Bullet>()) { realm.ModifyEntity(entity); } foreach (var entity in realm.Entities.OfType<Gate>()) { realm.ModifyEntity(entity); } // It's time for sync if (DateTime.Now > _nextUpdate) { foreach (var ent in _list) { if (ent.Value == EntityState.Added) _service.AddEntity(ent.Key); if (ent.Value == EntityState.Modified) _service.ModifyEntity(ent.Key); if (ent.Value == EntityState.Removed) _service.RemoveEntity(ent.Key); } _list.Clear(); _nextUpdate = DateTime.Now.AddMilliseconds(100); } }
private void btnSetLoginRoom_Click(object sender, EventArgs e) { frmLoginRoom form = new frmLoginRoom(); form.ShowDialog(); while (form.Visible) { Application.DoEvents(); } form = null; //Reset the login room text bool good = false; if (EngineSettings.Default.InitialRoom != null) { string[] env = EngineSettings.Default.InitialRoom.Split('>'); if (env.Length == 3) { IRealm realm = Editor.Game.World.GetRealm(env[0]); if (realm != null) { IZone zone = realm.GetZone(env[1]); if (zone != null) { IRoom room = zone.GetRoom(env[2]); if (room != null) { lblLoginRoom.Text = string.Format("Login Room: {0}>{1}>{2}", realm.Name, zone.Name, room.Name); good = true; } } } } } if (!good) { lblLoginRoom.Text = "Login Room: None set."; } }
private async Task AwaitReceiveAsync(IClient client, IRealm realm, CancellationToken cancellationToken = default) { var socket = client.GetSocket(); var buffer = new ArraySegment <byte>(new byte[1024 * 16]); WebSocketReceiveResult result; do { var(readResult, message) = await ReadAsync(socket, buffer, cancellationToken); await HandleMessageAsync(client, message, realm, cancellationToken); result = readResult; }while (!result.CloseStatus.HasValue); await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, cancellationToken); }
private async Task PruneZombieConnectionsAsync(IRealm realm) { var clientIds = realm.GetClientIds(); var now = DateTime.UtcNow; var aliveTimeout = TimeSpan.FromSeconds(60); var count = 0; foreach (var clientId in clientIds) { var client = realm.GetClient(clientId); var timeSinceLastHeartbeat = now - client.GetLastHeartbeat(); if (timeSinceLastHeartbeat < aliveTimeout) { continue; } var socket = client.GetSocket(); try { await socket?.CloseAsync($"Zombie connection, time since last heartbeat: {timeSinceLastHeartbeat.TotalSeconds}s"); } finally { realm.ClearMessageQueue(clientId); realm.RemoveClientById(clientId); socket?.Dispose(); } count++; } _logger.LogInformation($"Pruned zombie connections for {count} peers."); }
private void comRealms_SelectedIndexChanged(object sender, EventArgs e) { zonesLstExistingZones.Items.Clear(); IRealm realm = Editor.Game.World.GetRealm(comRealms.SelectedItem.ToString()); if (realm == null) { MessageBox.Show("Realm does not exist!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Editor.CurrentRealm = realm; IZone[] zones = realm.GetZones(); if (zones != null) { foreach (IZone zone in zones) { zonesLstExistingZones.Items.Add(zone.Name); } } UpdateUI(); }
private void frmEngineSettings_Load(object sender, EventArgs e) { //Load all of the scripts that have settings associated with them, store them and //present them to the GUI. ProcessScripts(); bool good = false; if (EngineSettings.Default.InitialRoom != null) { string[] env = EngineSettings.Default.InitialRoom.Split('>'); if (env.Length == 3) { IRealm realm = Editor.Game.World.GetRealm(env[0]); if (realm != null) { IZone zone = realm.GetZone(env[1]); if (zone != null) { IRoom room = zone.GetRoom(env[2]); if (room != null) { lblLoginRoom.Text = string.Format("Login Room: {0}>{1}>{2}", realm.Name, zone.Name, room.Name); good = true; } } } } } if (!good) { lblLoginRoom.Text = "Login Room: None set."; } }
private void RefreshRoomLabels(IRealm realm, IZone zone, IRoom room) { //If the room is null, tell the UI if (room == null) { roomsLblCurrentRoom.Text = "Current Room: None Loaded"; } //Otherwise, display the room name along with it's Type. else { roomsLblCurrentRoom.Text = "Current Room: " + room.Name + " (" + room.GetType().Name + ")"; } //If the Realm and Zone are null, warn if (realm == null || zone == null) { roomsLblRealmAndZone.Text = "No Location Loaded! New Rooms will be created within the Zone\nthat is selected under the Environments Tab."; } //Otherwise display the current Environment path for the loaded Room else { roomsLblRealmAndZone.Text = "Current Zone: " + realm.Name + "->" + zone.Name; } }
/// <summary>Calculates physics and updates entities.</summary> /// <param name="realm">Realm.</param> /// <param name="delta">Delta time.</param> public override void Update(IRealm realm, double delta) { // Update physics _world.Step((float)delta); // Update entities foreach (var entity in _entities) { var e = entity.Key; var body = entity.Value; if (e.GetType() == typeof(Player)) { var player = (Player)e; player.X = body.Position.X; player.Y = body.Position.Y; //body.LinearVelocity = new Vector2(player.VectorX, player.VectorY); body.ApplyLinearImpulse(new Vector2(player.VectorX, player.VectorY)); } if (e.GetType() == typeof(Ball)) { var ball = (Ball)e; ball.X = body.Position.X; ball.Y = body.Position.Y; body.ApplyLinearImpulse(new Vector2(ball.VectorX, ball.VectorY)); ball.VectorX = ball.VectorY = 0; } if (e.GetType() == typeof(Bullet)) { var bullet = (Bullet)e; bullet.X = body.Position.X; bullet.Y = body.Position.Y; if (body.LinearVelocity.Length() < 1) body.ApplyForce(new Vector2(bullet.VectorX, bullet.VectorY)); //bullet.VectorX = bullet.VectorY = 0; } } }
/// <summary>Entity modified.</summary> /// <param name="realm">Realm.</param> /// <param name="entity">Entity.</param> public virtual void ModifyEntity(IRealm realm, object entity) { }
/// <summary>New user joined to the game as player.</summary> /// <param name="user">User.</param> /// <returns>Aceept user to the game?</returns> public virtual bool Join(IRealm realm, User user, Team team) { return true; }
public MSSqlExport(ICustomLogger logger, IRealm realm, ISendMessageEvent sendMessageEvent) { _logger = logger; _realm = realm; _sendMessageEvent = sendMessageEvent; }
/// <summary>User outs from the game.</summary> /// <param name="user">User.</param> public virtual void Leave(IRealm realm, User user) { }
public void Add(IRealm realm) { realm.Begin(); realmQueue.Enqueue(realm); }
/// <summary> /// Initializes a new instance of the <see cref="MudZone"/> class. /// </summary> /// <param name="weatherStates">The weather states that can be applied to this zone.</param> public MudZone(IRoomFactory roomFactory, IRealm owner, IEnumerable<IWeatherState> weatherStates) : this(roomFactory, owner) { this.weatherStates = new List<IWeatherState>(weatherStates); }
/// <summary>Calls then realm started.</summary> /// <param name="realm">Realm.</param> public virtual void Start(IRealm realm) { }
/// <summary>Calls then realm updateing.</summary> /// <param name="realm">Realm.</param> /// <param name="delta">Time passed since last update.</param> public virtual void Update(IRealm realm, double delta) { }
/// <summary> /// Creates a new uninitialized zone. /// Each of the rooms added will be initialized prior to adding it to the zone. /// </summary> /// <param name="name">The name of the zone.</param> /// <param name="owner">The realm that owns this zone.</param> /// <param name="rooms">A collection of rooms that will be initialized and added to the zone.</param> /// <returns>Returns an uninitialized zone instance</returns> public Task<IZone> CreateZone(string name, IRealm owner, IEnumerable<IRoom> rooms) => this.CreateZone(name, owner, Enumerable.Empty<IWeatherState>(), 0, rooms);
/// <summary>User's input data received.</summary> /// <param name="realm">Realm.</param> /// <param name="user">User.</param> /// <param name="state">Keys and mouse events.</param> public virtual void Input(IRealm realm, User user, InputState state) { }
/// <summary> /// Creates a new uninitialized zone. /// </summary> /// <param name="name">The name of the zone.</param> /// <param name="owner">The realm that owns this zone.</param> /// <param name="weatherStates">The weather states to be made available in the zone.</param> /// <param name="weatherUpdateFrequency">The frequency to which the weather should be updated.</param> /// <returns> /// Returns an uninitialized zone instance /// </returns> public Task<IZone> CreateZone(string name, IRealm owner, IEnumerable<IWeatherState> weatherStates, int weatherUpdateFrequency) => this.CreateZone(name, owner, weatherStates, weatherUpdateFrequency, Enumerable.Empty<IRoom>());
/// <summary>User outs from the game.</summary> /// <param name="realm">Realm.</param> /// <param name="user">User.</param> public override void Leave(IRealm realm, User user) { realm.RemoveEntity(user["player"]); }
/// <summary>Entity removed.</summary> /// <param name="realm">Realm.</param> /// <param name="entity">Entity.</param> public virtual void RemoveEntity(IRealm realm, object entity) { }