protected override void ExecutionImpl(IEsbChannel esbChannel, IDSFDataObject dataObject, string inputs, string outputs, out ErrorResultTO tmpErrors, int update)
        {
            tmpErrors = new ErrorResultTO();
            try
            {
                if (Method == null)
                {
                    throw new Exception(ErrorResource.NoMethodSelected);
                }

                ExecuteService(update, out tmpErrors, Method, dataObject, OutputFormatterFactory.CreateOutputFormatter(OutputDescription));
            }
            catch (Exception err)
            {
                tmpErrors.AddError(err.Message);
            }
            finally
            {
                if (tmpErrors.HasErrors())
                {
                    foreach (var error in tmpErrors.FetchErrors())
                    {
                        dataObject.Environment.AddError(error);
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Character "Shout" method
        /// </summary>
        /// <param name="speech">What the character is "Shouting"</param>
        /// <param name="charSpeaking">The character who is speaking</param>
        public void ChatShout(string speech, SMCharacter charSpeaking)
        {
            // variable for the message sending used later.
            string message;

            // Send the message to all people connected to the room
            foreach (SMCharacter smc in this.GetPeople())
            {
                // construct the local message to be sent.
                message = OutputFormatterFactory.Get().Bold(charSpeaking.GetFullName() + " shouts:", 0) + " \"" + speech + "\"";
                this.ChatSendMessage(smc, message);
            }

            // Send a message to people connected to rooms around this room
            foreach (SMExit sme in this.RoomExits)
            {
                // Get the room details from the exit id
                SMRoom otherRooms = new SMRoom();

                otherRooms = new SlackMud().GetRoom(sme.RoomID);

                // Get the "from" location
                SMExit smre = otherRooms.RoomExits.FirstOrDefault(smef => smef.RoomID == this.RoomID);

                // Construct the message
                message = OutputFormatterFactory.Get().Italic("Someone shouts from " + smre.Description + " (" + smre.Shortcut + "):", 0) + " \"" + speech + "\"";

                // Send the message to all people connected to the room
                foreach (SMCharacter smcInOtherRoom in otherRooms.GetPeople())
                {
                    otherRooms.ChatSendMessage(smcInOtherRoom, message);
                }
            }
        }
Exemplo n.º 3
0
        private void ProcessResponse(NPCResponses npr, SMCharacter invokingCharacter, SMItem itemIn)
        {
            // Process each of the response steps
            foreach (NPCResponseStep NPCRS in npr.ResponseSteps)
            {
                // Get the invoking character
                invokingCharacter = new SlackMud().GetCharacter(invokingCharacter.UserID);

                // Check the character is still in the same room
                if (invokingCharacter.RoomID == this.RoomID)
                {
                    switch (NPCRS.ResponseStepType)
                    {
                    case "Conversation":
                        ProcessConversation(NPCRS, invokingCharacter);
                        break;

                    case "Attack":
                        this.Attack(invokingCharacter.GetFullName());
                        break;

                    case "UseSkill":
                        string[] dataSplit = null;
                        if (NPCRS.ResponseStepData.Contains('.'))
                        {
                            dataSplit = NPCRS.ResponseStepData.Split('.');
                        }
                        else
                        {
                            dataSplit[0] = NPCRS.ResponseStepData;
                            dataSplit[1] = null;
                        }

                        this.UseSkill(dataSplit[0], dataSplit[1]);
                        break;

                    case "ItemCheck":
                        // Get the additional data
                        string[] itemType = npr.AdditionalData.Split('.');

                        if (itemType[0] == "Family")
                        {
                            if (itemIn.ItemFamily != itemType[1])
                            {
                                // Drop the item
                                this.GetRoom().AddItem(itemIn);
                                this.GetRoom().Announce(OutputFormatterFactory.Get().Italic($"\"{this.GetFullName()}\" dropped {itemIn.SingularPronoun} {itemIn.ItemName}."));
                            }
                            else
                            {
                                ProcessConversation(NPCRS, invokingCharacter);
                            }
                        }

                        break;
                    }
                }
            }
        }
Exemplo n.º 4
0
        public void Spawn()
        {
            if (this.NPCSpawns != null)
            {
                // Only one thing at a time can spawn at the moment.
                bool         spawnedThisRound = false;
                List <SMNPC> smnpcl           = new List <SMNPC>();

                // loop around the spawns
                foreach (SMSpawn sms in this.NPCSpawns)
                {
                    // random number between 1 and 100
                    int randomChance = (new Random().Next(1, 100));

                    if (!spawnedThisRound)
                    {
                        // Check if we should try spawning
                        if (randomChance < sms.SpawnFrequency)
                        {
                            // Check if it's a unique person
                            if (sms.Unique)
                            {
                                // Check if the unique NPC is already somewhere in the world...
                                smnpcl = (List <SMNPC>)HttpContext.Current.Application["SMNPCs"];
                                if (smnpcl.Count(npc => (npc.FirstName + npc.LastName) == sms.TypeOfNPC) == 0)
                                {
                                    // ... if they're not, spawn them into the room.
                                    SMNPC newNPC = NPCHelper.GetNewNPC(sms.TypeOfNPC, true);
                                    newNPC.RoomID = this.RoomID;
                                    smnpcl.Add(newNPC);
                                    HttpContext.Current.Application["SMNPCs"] = smnpcl;

                                    this.Announce(OutputFormatterFactory.Get().Italic(newNPC.GetFullName() + " walks in"));
                                }
                            }

                            if (!spawnedThisRound)
                            {
                                // Check how many there are of this type in the room already
                                int numberOfNPCsOfType = this.GetNPCs().Count(npc => npc.NPCType == sms.TypeOfNPC);

                                // If there are less NPCs than the max number of the type...
                                if (numberOfNPCsOfType < sms.MaxNumber)
                                {
                                    // .. add one
                                    SMNPC newNPC = NPCHelper.GetNewNPC(sms.TypeOfNPC);
                                    newNPC.RoomID = this.RoomID;
                                    smnpcl        = (List <SMNPC>)HttpContext.Current.Application["SMNPCs"];
                                    smnpcl.Add(newNPC);
                                    HttpContext.Current.Application["SMNPCs"] = smnpcl;

                                    this.Announce(OutputFormatterFactory.Get().Italic(newNPC.PronounSingular.ToUpper() + " " + newNPC.GetFullName() + " " + newNPC.WalkingType + "s in"));
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// SMHelp class constructor, populate commandsList
        /// </summary>
        public SMHelp(string UserId)
        {
            this.commandList = this.GetCommandsList();

            this.character = new SlackMud().GetCharacter(UserId);

            this.outputFormatter = OutputFormatterFactory.Get();
        }
Exemplo n.º 6
0
        public void Return_OutputFormatter_On_FormatterType(FormatterType formatterType, Type expectedType)
        {
            var factory = new OutputFormatterFactory();

            var formatter = factory.GetFormatter(formatterType);

            Assert.NotNull(formatter);
            Assert.IsType(expectedType, formatter);
        }
Exemplo n.º 7
0
        protected void ExecuteService(int update, out ErrorResultTO errors, IPluginAction method, INamespaceItem namespaceItem, IDSFDataObject dataObject)
        {
            errors = new ErrorResultTO();
            var itrs = new List<IWarewolfIterator>(5);
            IWarewolfListIterator itrCollection = new WarewolfListIterator();
            var methodParameters = Inputs.Select(a => new MethodParameter { EmptyToNull = a.EmptyIsNull, IsRequired = a.RequiredField, Name = a.Name, Value = a.Value, TypeName = a.TypeName }).ToList();
            BuildParameterIterators(update, methodParameters.ToList(), itrCollection, itrs, dataObject);
            var args = new PluginInvokeArgs
            {
                AssemblyLocation = Namespace.AssemblyLocation,
                AssemblyName = Namespace.AssemblyName,
                Fullname = namespaceItem.FullName,
                Method = method.Method,
                Parameters = methodParameters
            };

            try
            {
                while (itrCollection.HasMoreData())
                {
                    int pos = 0;
                    foreach (var itr in itrs)
                    {
                        string injectVal = itrCollection.FetchNextValue(itr);
                        var param = methodParameters.ToList()[pos];


                        param.Value = param.EmptyToNull &&
                                      (injectVal == null ||
                                       string.Compare(injectVal, string.Empty,
                                           StringComparison.InvariantCultureIgnoreCase) == 0)
                            ? null
                            : injectVal;

                        pos++;
                    }                    
                    if (!IsObject)
                    {
                        int i = 0;
                        foreach (var serviceOutputMapping in Outputs)
                        {
                            OutputDescription.DataSourceShapes[0].Paths[i].OutputExpression = DataListUtil.AddBracketsToValueIfNotExist(serviceOutputMapping.MappedTo);
                            i++;
                        }
                        var outputFormatter = OutputFormatterFactory.CreateOutputFormatter(OutputDescription);
                        args.OutputFormatter = outputFormatter;
                    }
                    var result = PluginServiceExecutionFactory.InvokePlugin(args).ToString();
                    ResponseManager = new ResponseManager { OutputDescription = OutputDescription, Outputs = Outputs, IsObject = IsObject, ObjectName = ObjectName };
                    ResponseManager.PushResponseIntoEnvironment(result, update, dataObject,false);
                }
            }
            catch (Exception e)
            {
                errors.AddError(e.Message);
            }
        }
Exemplo n.º 8
0
        public void Return_OutputFormatter_On_FormatterType_String(string formatterType, Type expectedType)
        {
            var factory = new OutputFormatterFactory();

            var formatter = factory.GetFormatter(formatterType);

            Assert.NotNull(formatter);
            Assert.Equal(expectedType, formatter.GetType());
        }
Exemplo n.º 9
0
 protected override void ExecutionImpl(IEsbChannel esbChannel, IDSFDataObject dataObject, string inputs, string outputs, out ErrorResultTO tmpErrors, int update)
 {
     tmpErrors = new ErrorResultTO();
     if (Method == null)
     {
         tmpErrors.AddError(ErrorResource.NoMethodSelected);
         return;
     }
     ExecuteService(update, out tmpErrors, Method, dataObject, OutputFormatterFactory.CreateOutputFormatter(OutputDescription));
 }
Exemplo n.º 10
0
        /// <summary>
        /// Character "SAY" method
        /// </summary>
        /// <param name="speech">What the character is "Saying"</param>
        /// <param name="charSpeaking">The character who is speaking</param>
        public void ChatSay(string speech, SMCharacter charSpeaking)
        {
            // Construct the message
            string message = OutputFormatterFactory.Get().Italic(charSpeaking.GetFullName() + " says:", 0) + " \"" + speech + "\"";

            // Send the message to all people connected to the room
            foreach (SMCharacter smc in this.GetPeople())
            {
                this.ChatSendMessage(smc, message);
            }
        }
Exemplo n.º 11
0
        public void PushResponseIntoEnvironment(string input, int update, IDSFDataObject dataObj, bool formatResult = true)
        {
            if (dataObj == null)
            {
                throw new ArgumentNullException(nameof(dataObj));
            }

            try
            {
                if (IsObject)
                {
                    var jContainer = JsonConvert.DeserializeObject(input) as JContainer;
                    dataObj.Environment.AddToJsonObjects(ObjectName, jContainer);
                }
                else
                {
                    if (Outputs == null || Outputs.Count == 0)
                    {
                        return;
                    }
                    IOutputFormatter formater = null;
                    if (OutputDescription != null)
                    {
                        int i = 0;
                        foreach (var serviceOutputMapping in Outputs)
                        {
                            OutputDescription.DataSourceShapes[0].Paths[i].OutputExpression = DataListUtil.AddBracketsToValueIfNotExist(serviceOutputMapping.MappedTo);
                            i++;
                        }
                        if (OutputDescription.DataSourceShapes.Count == 1 && OutputDescription.DataSourceShapes[0].Paths.All(a => a is StringPath))
                        {
                            var serviceOutputMapping = Outputs.First();
                            if (serviceOutputMapping != null)
                            {
                                dataObj.Environment.Assign(serviceOutputMapping.MappedTo, input, update);
                            }
                            return;
                        }
                        formater = OutputFormatterFactory.CreateOutputFormatter(OutputDescription);
                    }
                    if (!string.IsNullOrEmpty(input))
                    {
                        FormatForOutput(input, update, dataObj, formatResult, formater);
                    }
                }
            }
            catch (Exception e)
            {
                dataObj.Environment.AddError(e.Message);
                Dev2Logger.Error(e.Message, e);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Character "Whisper" method
        /// </summary>
        /// <param name="speech">What the character is "Whispering"</param>
        /// <param name="charSpeaking">The character who is speaking</param>
        /// /// <param name="whisperToName">The character who is being whispered to</param>
        public void ChatWhisper(string speech, SMCharacter charSpeaking, string whisperToName)
        {
            // Construct the message
            string message = OutputFormatterFactory.Get().Italic(charSpeaking.GetFullName() + " whispers:", 0) + " \"" + speech + "\"";

            // See if the person being whispered to is in the room
            SMCharacter smc = this.GetPeople().FirstOrDefault(charWhisperedto => charWhisperedto.GetFullName() == whisperToName);

            if (smc != null)
            {
                this.ChatSendMessage(smc, message);
            }
            else
            {
                message = "That person doesn't appear to be here?";
                // TODO Send message to player to say they can't whisper to that person.
            }
        }
Exemplo n.º 13
0
        void TryFormatOutput(string input, int update, IDSFDataObject dataObj, bool formatResult)
        {
            IOutputFormatter formater = null;

            if (OutputDescription != null)
            {
                var i = 0;
                foreach (var serviceOutputMapping in Outputs)
                {
                    OutputDescription.DataSourceShapes[0].Paths[i].OutputExpression = !string.IsNullOrEmpty(DataListUtil.RemoveLanguageBrackets(serviceOutputMapping.MappedTo)) ? DataListUtil.AddBracketsToValueIfNotExist(serviceOutputMapping.MappedTo) : string.Empty;
                    i++;
                }
                formater = OutputFormatterFactory.CreateOutputFormatter(OutputDescription);
            }
            if (!string.IsNullOrEmpty(input))
            {
                FormatForOutput(input, update, dataObj, formatResult, formater);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Character "EMOTE" method
        /// </summary>
        /// <param name="emoting">What the character is "Emoting"</param>
        /// <param name="charSpeaking">The character who is emoting</param>
        public void ChatEmote(string speech, SMCharacter charSpeaking, SMNPC charNPCSpeak = null)
        {
            // Construct the message
            // Precursor items for generic NPCs
            string precursor = "";

            if ((charNPCSpeak != null) && (charNPCSpeak.IsGeneric))
            {
                precursor = charNPCSpeak.PronounSingular.ToUpper() + " ";
            }

            // Output the message
            string message = OutputFormatterFactory.Get().Italic(precursor + charSpeaking.GetFullName() + " " + speech);

            // Send the message to all people connected to the room
            foreach (SMCharacter smc in this.GetPeople())
            {
                this.ChatSendMessage(smc, message);
            }
        }
Exemplo n.º 15
0
        private void PerfromExecution(int update, IDSFDataObject dataObject, ComPluginInvokeArgs args)
        {
            if (!IsObject)
            {
                int i = 0;
                foreach (var serviceOutputMapping in Outputs)
                {
                    OutputDescription.DataSourceShapes[0].Paths[i].OutputExpression = DataListUtil.AddBracketsToValueIfNotExist(serviceOutputMapping.MappedTo);
                    i++;
                }
                var outputFormatter = OutputFormatterFactory.CreateOutputFormatter(OutputDescription);
                args.OutputFormatter = outputFormatter;
            }
            Common.Utilities.PerformActionInsideImpersonatedContext(Common.Utilities.ServerUser, () => { _result = ComPluginServiceExecutionFactory.InvokeComPlugin(args).ToString(); });

            ResponseManager = new ResponseManager {
                OutputDescription = OutputDescription, Outputs = Outputs, IsObject = IsObject, ObjectName = ObjectName
            };
            ResponseManager.PushResponseIntoEnvironment(_result, update, dataObject, false);
        }
        private void convertButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ViewModel.Validate();

                var converter = InputConverterFactory.Build(ViewModel);
                var questions = converter.Convert().ToArray();

                var formatter = OutputFormatterFactory.Build(ViewModel);
                formatter.Format(questions);

                MessageBox.Show(this, $"Generated file at '{ViewModel.DestinationFile}' with {questions.Length} questions.",
                                "Test Creator", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Test Creator", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 17
0
        void PerformExecution(int update, IDSFDataObject dataObject, ComPluginInvokeArgs args)
        {
            if (!IsObject)
            {
                var i = 0;
                foreach (var serviceOutputMapping in Outputs)
                {
                    OutputDescription.DataSourceShapes[0].Paths[i].OutputExpression = DataListUtil.AddBracketsToValueIfNotExist(serviceOutputMapping.MappedTo);
                    i++;
                }
                var outputFormatter = OutputFormatterFactory.CreateOutputFormatter(OutputDescription);
                args.OutputFormatter = outputFormatter;
            }
            ExecuteInsideImpersonatedContext(args);

            ResponseManager            = _responseManagerFactory.New(OutputDescription);
            ResponseManager.Outputs    = Outputs;
            ResponseManager.IsObject   = IsObject;
            ResponseManager.ObjectName = ObjectName;
            ResponseManager.PushResponseIntoEnvironment(_result, update, dataObject, false);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Performs program execution with valid options.
        /// </summary>
        /// <param name="options">Program run options</param>
        private static int RunWithParsed(Options options)
        {
            try
            {
                var converter = InputConverterFactory.Build(options);
                var questions = converter.Convert();

                var formatter = OutputFormatterFactory.Build(options);
                formatter.Format(questions);

                Logger.Log(Logger.Type.Success, $"Generated file at '{options.DestFile}' with {questions.Count()} questions.");

                return(0);
            }
            catch (Exception ex)
            {
                Logger.Log(Logger.Type.Error, ex.Message);

                return(1);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Gets the items listing of a given container in a string ready for outputting.
        /// </summary>
        /// <param name="container">Container SMItem to get the listings for.</param>
        /// <returns>Containers item listings.</returns>
        public static string GetContainerContents(SMItem container)
        {
            // Return null it not a container
            if (!container.CanHoldOtherItems())
            {
                return(null);
            }

            // If the container is empty
            if (container.HeldItems == null || !container.HeldItems.Any())
            {
                return(OutputFormatterFactory.Get().Italic("Empty"));
            }

            // Get list of item counts
            // TODO bring this functionality into this class
            List <ItemCountObject> lines = SMItemUtils.GetItemCountList(container.HeldItems);

            string output = "";

            foreach (ItemCountObject line in lines)
            {
                string itemDetails = $"{line.Count} x ";

                if (line.Count > 1)
                {
                    itemDetails += line.PluralName;
                }
                else
                {
                    itemDetails += line.SingularName;
                }

                output += OutputFormatterFactory.Get().General(itemDetails);
            }

            return(output);
        }
Exemplo n.º 20
0
        public string GetLocationDetails(string roomID, string userID = "0")
        {
            // Variable for the return string
            string returnString = "";

            // Get the room from memory
            SMRoom smr = GetRoom(roomID);

            // Check if the character exists..
            if (smr == null)
            {
                // If they don't exist inform the person as to how to create a new user
                returnString = OutputFormatterFactory.Get().Italic("Location does not exist?  Please report this as an error to [email protected]");
            }
            else
            {
                // Return the room description, exits, people and objects
                returnString = smr.GetLocationInformation(userID);
            }

            // Return the text output
            return(returnString);
        }
Exemplo n.º 21
0
        private void TryExecute(int update, IDSFDataObject dataObject, List <IWarewolfIterator> itrs, IWarewolfListIterator itrCollection, List <MethodParameter> methodParameters, PluginInvokeArgs args)
        {
            while (itrCollection.HasMoreData())
            {
                var pos = 0;
                foreach (var itr in itrs)
                {
                    var injectVal = itrCollection.FetchNextValue(itr);
                    var param     = methodParameters.ToList()[pos];

                    param.Value = param.EmptyToNull &&
                                  (injectVal == null ||
                                   string.Compare(injectVal, string.Empty,
                                                  StringComparison.InvariantCultureIgnoreCase) == 0)
                        ? null
                        : injectVal;

                    pos++;
                }
                if (!IsObject)
                {
                    var i = 0;
                    foreach (var serviceOutputMapping in Outputs)
                    {
                        OutputDescription.DataSourceShapes[0].Paths[i].OutputExpression = DataListUtil.AddBracketsToValueIfNotExist(serviceOutputMapping.MappedTo);
                        i++;
                    }
                    var outputFormatter = OutputFormatterFactory.CreateOutputFormatter(OutputDescription);
                    args.OutputFormatter = outputFormatter;
                }
                var result = PluginServiceExecutionFactory.InvokePlugin(args).ToString();
                ResponseManager = new ResponseManager {
                    OutputDescription = OutputDescription, Outputs = Outputs, IsObject = IsObject, ObjectName = ObjectName
                };
                ResponseManager.PushResponseIntoEnvironment(result, update, dataObject, false);
            }
        }
 protected virtual IOutputFormatter GetOutputFormatter(TService service)
 {
     return(OutputFormatterFactory.CreateOutputFormatter(service.OutputDescription, "root"));
 }
Exemplo n.º 23
0
 /// <summary>
 /// Formats a given text string for a given output channel, replacing/stripping tags as required.
 /// </summary>
 /// <param name="platform">The target platform where the text will be outputted.</param>
 /// <param name="message">The text output to format.</param>
 /// <returns>The formatted text.</returns>
 private static string GetFormattedMessage(string platform, string message)
 {
     return(OutputFormatterFactory.Get(platform).ProcessOutput(message));
 }
Exemplo n.º 24
0
 IOutputFormatter GetOutputFormatter(TService service) => OutputFormatterFactory.CreateOutputFormatter(service.OutputDescription, "root");
Exemplo n.º 25
0
        /// <summary>
        /// Inspect a person, object, etc.
        /// </summary>
        /// <param name="smc">The character doing the inspecting</param>
        /// <param name="thingToInspect">The thing that the person wants to inspect</param>
        public void InspectThing(SMCharacter smc, string thingToInspect)
        {
            // Check if it's a character first
            SMCharacter targetCharacter = this.GetPeople().FirstOrDefault(checkChar => checkChar.GetFullName().ToLower() == thingToInspect.ToLower());

            if (targetCharacter != null)
            {
                smc.sendMessageToPlayer(OutputFormatterFactory.Get().Bold("Description of " + targetCharacter.GetFullName() + " (Level " + targetCharacter.CalculateLevel() + "):"));
                if ((targetCharacter.Description != null) || (targetCharacter.Description != ""))
                {
                    smc.sendMessageToPlayer(OutputFormatterFactory.Get().Italic(targetCharacter.Description));
                }
                else
                {
                    smc.sendMessageToPlayer(OutputFormatterFactory.Get().Italic("No description set..."));
                }
                smc.sendMessageToPlayer(OutputFormatterFactory.Get().CodeBlock(targetCharacter.GetInventoryList()));
                targetCharacter.sendMessageToPlayer(OutputFormatterFactory.Get().Italic(smc.GetFullName() + " looks at you"));
                return;
            }

            // If not a character, check if it is an NPC...
            SMNPC targetNPC = this.GetNPCs().FirstOrDefault(checkChar => checkChar.GetFullName().ToLower() == thingToInspect.ToLower());

            if (targetNPC != null)
            {
                smc.sendMessageToPlayer(OutputFormatterFactory.Get().Bold("Description of " + targetNPC.GetFullName() + " (Level " + targetNPC.CalculateLevel() + "):"));
                if ((targetNPC.Description != null) || (targetNPC.Description != ""))
                {
                    smc.sendMessageToPlayer(OutputFormatterFactory.Get().Italic(targetNPC.Description));
                }
                else
                {
                    smc.sendMessageToPlayer(OutputFormatterFactory.Get().Italic("No description set..."));
                }
                smc.sendMessageToPlayer(OutputFormatterFactory.Get().CodeBlock(targetNPC.GetInventoryList()));
                targetNPC.GetRoom().ProcessNPCReactions("PlayerCharacter.ExaminesThem", smc, targetNPC.UserID);
                targetNPC.GetRoom().ProcessNPCReactions("PlayerCharacter.Examines", smc);
                return;
            }

            // If not an NPC, check the players equipped items and the items in the room...
            SMItem smi = smc.GetEquippedItem(thingToInspect);

            if (smi == null)
            {
                smi = SMItemHelper.GetItemFromList(this.RoomItems, thingToInspect);
            }

            if (smi != null)
            {
                string itemDeatils = OutputFormatterFactory.Get().Bold("Description of \"" + smi.ItemName + "\":");
                itemDeatils += OutputFormatterFactory.Get().ListItem(smi.ItemDescription);

                if (smi.CanHoldOtherItems())
                {
                    itemDeatils += OutputFormatterFactory.Get().Italic($"This \"{smi.ItemName}\" contains the following items:");
                    itemDeatils += SMItemHelper.GetContainerContents(smi);
                }

                smc.sendMessageToPlayer(itemDeatils);
                return;
            }

            // Otherwise nothing found
            smc.sendMessageToPlayer(OutputFormatterFactory.Get().Italic("Can not inspect that item."));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Pulse the world
        /// </summary>
        public void Pulse()
        {
            // Work out the start time
            int currentUnixTime = Utility.Utils.GetUnixTime();

            // Get ingame date time info
            SMDay smd = new SMDay();

            smd = (SMDay)HttpContext.Current.Application["SMDay"];
            int totalDayNightHours          = 24 / (smd.LengthOfDay + smd.LengthOfNight);
            int numberOfMinutesPerGameDay   = totalDayNightHours * 60;
            int numberOfMinutesPerDayTime   = (numberOfMinutesPerGameDay / (smd.LengthOfDay + smd.LengthOfNight)) * smd.LengthOfDay;
            int numberOfMinutesPerNightTime = (numberOfMinutesPerGameDay / (smd.LengthOfDay + smd.LengthOfNight)) * smd.LengthOfNight;

            List <SMNotices> smn = (List <SMNotices>)HttpContext.Current.Application["SMNotices"];

            // Update in game time
            int    newTime    = this.TimeOfDay + (Utility.Utils.GetDifferenceBetweenUnixTimestampsInMinutes(this.LastUpdate, currentUnixTime) * totalDayNightHours);
            string dayOrNight = HttpContext.Current.Application["DayOrNight"].ToString();

            if (newTime > numberOfMinutesPerGameDay)
            {
                string noticeS = smn.FirstOrDefault(notice => notice.NoticeType == "DayStart").Notice ?? "A new day begins...";
                newTime = newTime - numberOfMinutesPerGameDay;
                new SlackMud().BroadcastMessage(OutputFormatterFactory.Get().Italic(noticeS));
                HttpContext.Current.Application["DayOrNight"] = "D";
            }
            else if ((newTime > numberOfMinutesPerDayTime) && (HttpContext.Current.Application["DayOrNight"].ToString() != "N"))
            {
                string noticeS = smn.FirstOrDefault(notice => notice.NoticeType == "NightStart").Notice ?? "Night falls";
                new SlackMud().BroadcastMessage(OutputFormatterFactory.Get().Italic(noticeS));
                HttpContext.Current.Application["DayOrNight"] = "N";
            }

            // Update the variables
            this.LastUpdate = currentUnixTime;
            this.TimeOfDay  = newTime;

            // NPC Cycles in the game world
            List <SMNPC> smnpcl = new List <SMNPC>();

            smnpcl = (List <SMNPC>)HttpContext.Current.Application["SMNPCs"];

            if (smnpcl != null)
            {
                smnpcl = smnpcl.FindAll(npc => npc.NPCResponses.Count(response => response.ResponseType == "Pulse") > 0);
                if (smnpcl != null)
                {
                    foreach (SMNPC npc in smnpcl)
                    {
                        npc.RespondToAction("Pulse", null);
                    }
                }
            }

            // Spawns
            // Find all rooms that are in memory that could have a spawn
            List <SMRoom> smrl = new List <SMRoom>();

            smrl = (List <SMRoom>)HttpContext.Current.Application["SMRooms"];

            // If there are any rooms in memory...
            if (smrl != null)
            {
                // ... find the rooms that have any possible spawns.
                smrl = smrl.FindAll(room => room.NPCSpawns != null);
                if (smrl != null)
                {
                    // loop around the rooms
                    foreach (SMRoom smr in smrl)
                    {
                        // Check whether there are any spawns.
                        smr.Spawn();
                    }
                }
            }

            // TODO Randonly decide whether the weather effect will change.


            // Work out the end time
            // If less than two minutes
            // Let the thread sleep for the remainder of the time
            int timeToWait = Utility.Utils.GetDifferenceBetweenUnixTimestamps(currentUnixTime, Utility.Utils.GetUnixTime());

            // If the time between the pulses is less than two minutes...
            if (timeToWait < (120 * 1000))
            {
                // ... send the thread to sleep
                Thread.Sleep((120 * 1000) - timeToWait);
            }

            // Recall the pulse.
            Pulse();
        }
 private IOutputFormatter GetOutputFormatter(TService service)
 {
     return(OutputFormatterFactory.CreateOutputFormatter(service.OutputDescription, "root"));
 }
Exemplo n.º 28
0
        private void ProcessConversationStep(NPCConversations npcc, string stepID, SMCharacter invokingCharacter)
        {
            NPCConversationStep npccs = npcc.ConversationSteps.FirstOrDefault(cs => cs.StepID == stepID);
            bool continueToNextStep   = true;

            if (npccs != null)
            {
                switch (npccs.Scope.ToLower())
                {
                case "choice":
                    string[] choices       = npccs.AdditionalData.Split(',');
                    int      choicesNumber = choices.Count();
                    int      randomChoice  = (new Random().Next(1, choicesNumber + 1)) - 1;
                    if (randomChoice > choicesNumber)
                    {
                        randomChoice = 0;
                    }
                    ProcessConversationStep(npcc, choices[randomChoice], invokingCharacter);
                    break;

                case "say":
                    this.Say(ProcessResponseString(npccs.AdditionalData, invokingCharacter));
                    break;

                case "shout":
                    this.Shout(ProcessResponseString(npccs.AdditionalData, invokingCharacter));
                    break;

                case "whisper":
                    this.Whisper(ProcessResponseString(npccs.AdditionalData, invokingCharacter), invokingCharacter.GetFullName());
                    break;

                case "emote":
                    this.GetRoom().ChatEmote(ProcessResponseString(npccs.AdditionalData, invokingCharacter), this, this);
                    break;

                case "saytoplayer":
                    // Construct the message
                    string sayToPlayerMessage = OutputFormatterFactory.Get().Italic(this.GetFullName() + " says:", 0) + " \"" + ProcessResponseString(npccs.AdditionalData, invokingCharacter) + "\"";

                    // Send the message
                    invokingCharacter.sendMessageToPlayer(sayToPlayerMessage);
                    break;

                case "emotetoplayer":
                    // Construct the message
                    string emoteToPlayerMessage = OutputFormatterFactory.Get().Italic(this.GetFullName() + " " + ProcessResponseString(npccs.AdditionalData, invokingCharacter));

                    // Send the message
                    invokingCharacter.sendMessageToPlayer(emoteToPlayerMessage);
                    break;

                case "attack":
                    // Simply attack a target player
                    this.Attack(invokingCharacter.GetFullName());
                    break;

                case "giveitem":
                    // give an item to the player
                    string[] additionalDataSplit = npccs.AdditionalData.Split(',');
                    string[] itemParts           = additionalDataSplit[0].Split('.');

                    // Create the item..
                    if (itemParts.Count() == 2)
                    {
                        int numberToCreate = int.Parse(additionalDataSplit[1]);

                        // Create the right number of the items.
                        while (numberToCreate > 0)
                        {
                            // Get the item (with a new GUID)
                            SMItem itemBeingGiven = SMItemFactory.Get(itemParts[0], itemParts[1]);

                            // Pass it to the player
                            invokingCharacter.PickUpItem("", itemBeingGiven, true);

                            // Reduce the number to create
                            numberToCreate--;
                        }
                    }
                    break;

                case "addquest":
                    // Load the quest
                    SMQuest smq = SMQuestFactory.Get(npccs.AdditionalData);
                    if (smq != null)
                    {
                        invokingCharacter.AddQuest(smq);
                    }
                    break;

                case "updatequest":
                    // Load the quest
                    SMQuest qtu = SMQuestFactory.Get(npccs.AdditionalData);
                    if (qtu != null)
                    {
                        invokingCharacter.UpdateQuest(qtu);
                    }
                    break;

                case "checkquestinprogress":
                    // Check the quest log isn't null
                    if (invokingCharacter.QuestLog != null)
                    {
                        if (invokingCharacter.QuestLog.Count(questcheck => (questcheck.QuestName.ToLower() == npccs.AdditionalData.ToLower()) && (questcheck.Completed)) > 0)
                        {
                            continueToNextStep = false;
                        }
                    }
                    break;

                case "setplayerattribute":
                    // Add a response option
                    switch (npccs.AdditionalData.ToLower())
                    {
                    case "firstname":
                        invokingCharacter.FirstName = invokingCharacter.VariableResponse;
                        break;

                    case "lastname":
                        invokingCharacter.LastName = invokingCharacter.VariableResponse;
                        break;

                    case "sex":
                        invokingCharacter.Sex = char.Parse(invokingCharacter.VariableResponse);
                        break;
                    }
                    invokingCharacter.SaveToApplication();
                    invokingCharacter.SaveToFile();
                    break;

                case "setvariableresponse":
                    invokingCharacter.VariableResponse = npccs.AdditionalData.ToLower();
                    break;

                case "teachskill":
                    // Check if the player already has the skill
                    if (invokingCharacter.Skills == null)
                    {
                        invokingCharacter.Skills = new List <SMSkillHeld>();
                    }

                    // Get the skill and level to teach to
                    string[] skillToTeach = npccs.AdditionalData.Split('.');

                    // Check if the character already has the skill
                    if (invokingCharacter.Skills.Count(skill => skill.SkillName == skillToTeach[0]) == 0)
                    {
                        // Create a new skill help object
                        SMSkillHeld smsh = new SMSkillHeld();
                        smsh.SkillName  = skillToTeach[0];
                        smsh.SkillLevel = int.Parse(skillToTeach[1]);

                        // Finally add it to the player
                        invokingCharacter.Skills.Add(smsh);

                        // Save the player
                        invokingCharacter.SaveToApplication();
                        invokingCharacter.SaveToFile();

                        // Inform the player they have learnt a new skill
                        invokingCharacter.sendMessageToPlayer(OutputFormatterFactory.Get().Italic($"You learn a new skill: {smsh.SkillName}({smsh.SkillLevel})."));
                    }

                    break;

                case "wait":
                    System.Threading.Thread.Sleep(int.Parse(npccs.AdditionalData) * 1000);
                    break;
                }

                if (continueToNextStep)
                {
                    if (npccs.ResponseOptions != null)
                    {
                        if (npccs.ResponseOptions.Count > 0)
                        {
                            ProcessResponseOptions(npcc, npccs, invokingCharacter);
                        }
                    }

                    if (npccs.NextStep != null)
                    {
                        string[] splitNextStep = npccs.NextStep.Split('.');
                        if (splitNextStep[1] != "0")
                        {
                            System.Threading.Thread.Sleep(int.Parse(splitNextStep[1]) * 1000);
                        }
                        ProcessConversationStep(npcc, splitNextStep[0], invokingCharacter);
                    }
                }
            }
        }
Exemplo n.º 29
0
        public void ThrowException_On_Invalid_FormatterType(FormatterType formatterType)
        {
            var factory = new OutputFormatterFactory();

            Assert.Throws <NotSupportedException>(() => factory.GetFormatter(formatterType));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Process the response options for an action.
        /// </summary>
        /// <param name="npcc">The conversation that is taking place</param>
        /// <param name="npccs">The step in the conversation</param>
        /// <param name="invokingCharacter">The invoking character</param>
        private void ProcessResponseOptions(NPCConversations npcc, NPCConversationStep npccs, SMCharacter invokingCharacter)
        {
            // Set the response option variables up
            string responseOptions   = OutputFormatterFactory.Get().Bold(this.GetFullName() + " Responses:") + OutputFormatterFactory.Get().NewLine;
            bool   thereIsAnOption   = false;
            List <ShortcutToken> stl = new List <ShortcutToken>();

            // Loop around the options building up the various parts
            foreach (NPCConversationStepResponseOptions npcccsro in npccs.ResponseOptions)
            {
                // Variable to hold whether the response can be added - it may not be allowed due to some prereqs..
                bool canAddResponse = true;

                // Check if there is a prereq...
                if (npcccsro.PreRequisites != null)
                {
                    // get the quests for use later
                    List <SMQuestStatus> smqs = new List <SMQuestStatus>();
                    if (invokingCharacter.QuestLog != null)
                    {
                        smqs = invokingCharacter.QuestLog;
                    }

                    // .. if there is, loop around them.
                    foreach (NPCConversationStepResponseOptionsPreRequisites prereq in npcccsro.PreRequisites)
                    {
                        switch (prereq.Type)
                        {
                        case "HasDoneQuest":
                            if (smqs.Count(quest => (quest.QuestName == prereq.AdditionalData) && (quest.Completed)) == 0)
                            {
                                canAddResponse = false;
                            }
                            break;

                        case "InProgressQuest":
                            if (smqs.Count(quest => (quest.QuestName == prereq.AdditionalData) && (!quest.Completed)) == 0)
                            {
                                canAddResponse = false;
                            }
                            break;

                        case "HasNotDoneQuest":
                            if (smqs.Count(quest => (quest.QuestName == prereq.AdditionalData)) != 0)
                            {
                                canAddResponse = false;
                            }
                            break;

                        case "IsNotInProgressQuest":
                            if (smqs.Count(quest => (quest.QuestName == prereq.AdditionalData) && (!quest.Completed)) != 0)
                            {
                                canAddResponse = false;
                            }
                            break;
                        }
                    }
                }

                // Check that the response can be added
                if (canAddResponse)
                {
                    responseOptions += OutputFormatterFactory.Get().ListItem(ProcessResponseString(npcccsro.ResponseOptionText, invokingCharacter) + " (" + npcccsro.ResponseOptionShortcut + ")");
                    ShortcutToken st = new ShortcutToken();
                    st.ShortCutToken = npcccsro.ResponseOptionShortcut;
                    stl.Add(st);
                    thereIsAnOption = true;
                }
            }

            // If an option has been set..
            if (thereIsAnOption)
            {
                AddResponse(npcc, npccs, invokingCharacter, stl, responseOptions);
            }
        }