Exemplo n.º 1
0
        public void PickupItem()
        {
            //From Ground
            Point inventoryUserPosition = GetParent().GetComponent <SpriteAnimation>(ComponentType.SpriteAnimation).Position;
            var   a = GetParent().GetComponent <Actor>(ComponentType.Actor);

            if (a != null)
            {
                var i = a.Map.GetItemAt(inventoryUserPosition.X, inventoryUserPosition.Y);
                if (i != null)
                {
                    AddItem(i);
                    i.GetComponent <SpriteAnimation>(ComponentType.SpriteAnimation).IsVisible = false;
                    i.GetComponent <SpriteAnimation>(ComponentType.SpriteAnimation).Position  = new Point(0, 0);
                    if (GetParent().logger != null)
                    {
                        ColoredString str = new ColoredString("Item : ");
                        str += string.Format("{0}", i.NAME).CreateColored(Color.Cyan);
                        str += ", Picked up.".CreateColored(Color.White);
                        GetParent().logger.Write(str);
                    }
                }
                else
                {
                    if (GetParent().logger != null)
                    {
                        GetParent().logger.Write("There is no item to pick up.");
                    }
                }
            }
        }
Exemplo n.º 2
0
        public override void Show(bool modal)
        {
            if (IsVisible)
            {
                return;
            }

            Center();

            base.Show(modal);


            UpdateCharSheetColors();


            string[] items = new string[] { "Current Index:", SelectedCharacterIndex.ToString() + " ", ((char)SelectedCharacterIndex).ToString() };

            items[2] = items[2].PadRight(Width - 2 - (items[0].Length + items[1].Length));

            ColoredString text = items[0].CreateColored(Color.LightBlue, Color.Black, null) +
                                 items[1].CreateColored(Color.LightCoral, Color.Black, null) +
                                 items[2].CreateColored(Color.LightCyan, Color.Black, null);

            text.IgnoreBackground = true;
            text.IgnoreEffect     = true;

            Print(1, Height - 2, text);
        }
        public ParseCommandGradient(string parameters)
        {
            var badCommandException = new ArgumentException("command is invalid for Recolor: " + parameters);

            string[] parametersArray = parameters.Split(':');

            if (parametersArray.Length > 3)
            {
                CommandType = parametersArray[0] == "b" ? CommandTypes.Background : CommandTypes.Foreground;
                Counter     = Length = int.Parse(parametersArray[parametersArray.Length - 1], CultureInfo.InvariantCulture);

                bool keep;
                bool useDefault;

                List <Color> steps = new List <Color>();

                for (int i = 1; i < parametersArray.Length - 1; i++)
                {
                    steps.Add(Color.White.FromParser(parametersArray[i], out keep, out keep, out keep, out keep, out useDefault));
                }

                GradientString = new ColorGradient(steps.ToArray()).ToColoredString(new string(' ', Length));
            }

            else
            {
                throw badCommandException;
            }
        }
Exemplo n.º 4
0
        public static void PrintStyledText(this CellSurface surface, int x, int y, params ColoredString[] text)
        {
            var glyphs        = text.SelectMany(part => part.ToArray()).ToArray();
            var coloredString = new ColoredString(glyphs);

            surface.Print(x, y, coloredString);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Creates a <see cref="ColoredString"/> object from an existing string with the specified foreground and background, setting the ignore properties if needed.
        /// </summary>
        /// <param name="value">The current string.</param>
        /// <param name="foreground">The foreground color. If null, <see cref="ColoredString.IgnoreForeground"/> will be set.</param>
        /// <param name="background">The background color. If null, <see cref="ColoredString.IgnoreBackground"/> will be set.</param>
        /// <param name="spriteEffect">The background color. If null, <see cref="ColoredString.IgnoreEffect"/> will be set.</param>
        /// <returns>A <see cref="ColoredString"/> object instace.</returns>
        public static ColoredString CreateColored(this string value, Color?foreground = null, Color?background = null)
        {
            var stacks = new ParseCommandStacks();

            if (foreground.HasValue)
            {
                stacks.AddSafe(new ParseCommandRecolor()
                {
                    R = foreground.Value.R, G = foreground.Value.G, B = foreground.Value.B, A = foreground.Value.A, CommandType = CommandTypes.Foreground
                });
            }

            if (background.HasValue)
            {
                stacks.AddSafe(new ParseCommandRecolor()
                {
                    R = background.Value.R, G = background.Value.G, B = background.Value.B, A = background.Value.A, CommandType = CommandTypes.Background
                });
            }

            ColoredString newString = ColoredString.Parse(value, initialBehaviors: stacks);

            if (!foreground.HasValue)
            {
                newString.IgnoreForeground = true;
            }

            if (!background.HasValue)
            {
                newString.IgnoreBackground = true;
            }

            return(newString);
        }
Exemplo n.º 6
0
        public void CreateEquipped(IIndexedKeybinding[] keybindings)
        {
            int index         = 0;
            var equippedItems = InventoryManager.GetEquippedItems <PlayerInventory>();

            foreach (var item in keybindings)
            {
                ColoredString prefix       = new ColoredString();
                var           equippedItem = ItemManager.GetItem <IItem>(equippedItems[index].ObjectId);

                ColoredString itemName = ItemManager.GetItemName <IItem>(equippedItem.ObjectId);

                // temporary solution for item type formatting specifically for this window
                string itemType = equippedItem.GetType() == typeof(WeaponItem) ? "[WEAPON]" :
                                  equippedItem.GetType() == typeof(HeadItem) ? "[HEAD]" :
                                  equippedItem.GetType() == typeof(BodyItem) ? "[BODY]" :
                                  equippedItem.GetType() == typeof(LegsItem) ? "[LEGS]" : "UNKNOWN";

                string itemId = $"itemId_{equippedItem.ObjectId}";

                var printableItem = new PrintContainerBase()
                {
                    Name        = itemName,
                    Type        = itemType,
                    Data        = "\0",
                    Id          = "\0",
                    ButtonIndex = new ButtonIndex(keybindings[index].Key, Color.Green, Color.White, 0, 0, true)
                };

                _printable.Add(printableItem);
                index++;
            }
        }
Exemplo n.º 7
0
 public void AddText(ColoredString text, int lineNumber)
 {
     for (var i = 0; i < text.Length; i++)
     {
         Text[lineNumber, i + 2] = text[i];
     }
 }
Exemplo n.º 8
0
        public void CreateLocations(IIndexedKeybinding[] keybindings)
        {
            int index = 0;

            foreach (var item in keybindings)
            {
                var location = LocationManager.GetLocationByObjectId <ILocation>(item.ObjectId);

                ColoredString locationName = LocationManager.GetLocationName <ILocation>(location.ObjectId);

                if (location.ObjectId == Game.GameSession.Player.CurrentLocation.ObjectId)
                {
                    locationName.SetBackground(new Color(18, 77, 7));
                }

                var printableLocation = new PrintContainerBase()
                {
                    Name        = locationName,
                    Type        = location.MinLevel == 0 && location.MaxLevel == 0 ? "\0" : $"<{location.MinLevel} - {location.MaxLevel}>",
                    Data        = "\0",
                    Id          = "\0",
                    ButtonIndex = new ButtonIndex(keybindings[index].Key, Constants.Theme.ButtonKeyColor, Constants.Theme.ForegroundColor, 0, 0, true)
                };

                _printable.Add(printableLocation);
                index++;
            }
        }
Exemplo n.º 9
0
 protected virtual void GetColoredString(List <ColoredString> list)
 {
     if (this.SyntaxType == SyntaxType.WhiteSpaceTrivia)
     {
         list.Add(ColoredString.Create(this.text, ColorType.WhiteSpace));
     }
 }
Exemplo n.º 10
0
        public static void PrintHeader(ICellSurface target, SadConsole.UI.Colors themeColors, Point position, int totalWidth, string text)
        {
            totalWidth = totalWidth - text.Length - 3;

            if (totalWidth < 0)
            {
                throw new Exception("Header text too small");
            }

            var lineText = ColoredString.FromGradient(
                new Gradient(
                    new[] { themeColors.White, themeColors.White, themeColors.Gray, themeColors.Gray, themeColors.GrayDark, themeColors.GrayDark },
                    new[] { 0f, 0.3f, 0.31f, 0.65f, 0.66f, 1f }),
                new string((char)196, totalWidth));

            target.Print(position.X, position.Y, new ColoredString(new ColoredGlyph(themeColors.White, Color.Transparent, 196))
                         + new ColoredString(new ColoredGlyph(themeColors.Cyan, Color.Transparent, 254))
                         + new ColoredString(text, themeColors.Title, Color.Transparent)
                         + new ColoredString(new ColoredGlyph(themeColors.Cyan, Color.Transparent, 254))
                         );

            var targetPosition = Point.FromIndex(position.ToIndex(target.Width) + text.Length + 3, target.Width);

            target.Print(targetPosition.X, targetPosition.Y, lineText);
        }
Exemplo n.º 11
0
        // Calculates the outcome of a defender's attempt
        // at blocking incoming hits.
        // Modifies a StringBuilder messages that will be displayed
        // in the MessageLog, expressing the number of hits blocked.
        private static int ResolveDefense(Actor defender, int hits, ColoredString attackMessage, ColoredString defenseMessage)
        {
            int blocks = 0;

            if (hits > 0)
            {
                // Create a string that displays the defender's name and outcomes
                attackMessage.String  += ($"scoring {hits} hits.");
                defenseMessage.String += ($"{defender.Name} defends and rolls ");

                //The defender's Defense value determines the number of D100 dice rolled
                for (int i = 0; i < defender.Defense; i++)
                {
                    //Roll a single D100 and add its results to the defense Message
                    int diceOutcome = Dice.Roll("1d100");

                    //Resolve the dicing outcome and register a block, governed by the
                    //attacker's DefenceChance value.
                    if (diceOutcome >= 100 - defender.DefenseChance)
                    {
                        blocks++;
                    }
                }
                defenseMessage.String += ($"resulting in {blocks} blocks.");
            }
            else
            {
                attackMessage.String += ("and misses completely!;");
            }
            return(blocks);
        }
Exemplo n.º 12
0
        // Executes an attack from an attacking actor
        // on a defending actor, and then describes
        // the outcome of the attack in the Message Log
        public void Attack(Actor attacker, Actor defender)
        {
            // Create two messages that describe the outcome
            // of the attack and defense
            ColoredString attackMessage  = new ColoredString("");
            ColoredString defenseMessage = new ColoredString("");

            // Count up the amount of attacking damage done
            // and the number of successful blocks
            int hits   = ResolveAttack(attacker, defender, attackMessage);
            int blocks = ResolveDefense(defender, hits, attackMessage, defenseMessage);

            // Display the outcome of the attack & defense
            GameLoop.UIManager.MessageLog.Add(attackMessage);
            if (!string.IsNullOrWhiteSpace(defenseMessage.ToString()))
            {
                GameLoop.UIManager.MessageLog.Add(defenseMessage);
            }

            int damage = hits - blocks;

            // The defender now takes damage

            ResolveDamage(defender, damage);
        }
Exemplo n.º 13
0
        public override void FireEvent(object sender, EventArgs e)
        {
            if (e.GetType() == typeof(NewAttackEventArgs))
            {
                var hitPercent = ResolveAttack();
                var dmg        = AttackValue * hitPercent;

                System.Console.WriteLine(AttackValue);
                System.Console.WriteLine("Damage:{0}", (int)dmg);
                (e as NewAttackEventArgs).Damage = (int)dmg;

                //TODO: Modify Damage Here ?
                var        self_a = GetComponent <Actor>(ComponentType.Actor);
                BaseEntity other  = self_a.Map.GetEntityAt((e as NewAttackEventArgs).Position.X, (e as NewAttackEventArgs).Position.Y);
                if (other != null)
                {
                    if (GetParent().logger != null)
                    {
                        ColoredString str = new ColoredString(string.Format("{0}, ", GetParent().NAME));
                        str += "Attacks".CreateColored(Color.Red);
                        str += string.Format(" {0} for", other.NAME).CreateColored(Color.White);
                        str += string.Format(" {0} ", (int)dmg).CreateColored(Color.DarkRed);
                        str += "damage".CreateColored(Color.Red);
                        str += ".".CreateColored(Color.White);

                        GetParent().logger.Write(str);
                    }

                    other.FireEvent(this, new NewDamageEventArgs((e as NewAttackEventArgs).Damage));
                }
            }
        }
Exemplo n.º 14
0
        private void PrintNoCheck(int index, ColoredString text)
        {
            int total     = index + text.Count > textSurface.Cells.Length ? textSurface.Cells.Length : index + text.Count;
            int charIndex = 0;

            for (; index < total; index++)
            {
                if (!text.IgnoreGlyph)
                {
                    textSurface.Cells[index].Glyph = text[charIndex].GlyphCharacter;
                }
                if (!text.IgnoreBackground)
                {
                    textSurface.Cells[index].Background = text[charIndex].Background;
                }
                if (!text.IgnoreForeground)
                {
                    textSurface.Cells[index].Foreground = text[charIndex].Foreground;
                }
                if (!text.IgnoreMirror)
                {
                    textSurface.Cells[index].Mirror = text[charIndex].Mirror;
                }
                if (!text.IgnoreEffect)
                {
                    SetEffect(index, text[charIndex].Effect);
                }
                charIndex++;
            }
            textSurface.IsDirty = true;
        }
Exemplo n.º 15
0
        public SfmlApp()
        {
            InitGame();
            _window = InitGui();

            ColoredString.Write("You wake up in an Unknown world.");
        }
Exemplo n.º 16
0
        public void DrawMonsterStats(Monster monster, int monsterIdx)
        {
            // Start at Y=13 which is below the player stats.
            // Multiply the position by 2 to leave a space between each stat
            int yPosition = 13 + (monsterIdx * 2);

            // Begin the line by printing the symbol of the monster in the appropriate color
            Print(1, yPosition, monster.Symbol.ToString(), monster.color);

            // Figure out the width of the health bar by dividing current health by max health
            int width          = Convert.ToInt32(((double)monster.Health / monster.MaxHealth) * 16.0);
            int remainingWidth = 16 - width;

            // Set the background colors of the health bar to show how damaged the monster is
            ColoredString curHp = new ColoredString(width);

            curHp.SetBackground(Swatch.Primary);
            Print(3, yPosition, curHp);

            ColoredString missHp = new ColoredString(remainingWidth);

            missHp.SetBackground(Swatch.PrimaryDarkest);
            Print(3 + width, yPosition, missHp);

            // Print the monsters name over top of the health bar
            Print(2, yPosition, $": {monster.Name}", Swatch.DbLight);
        }
Exemplo n.º 17
0
        public UserVariableDefinition(StructDeclaratorSyntax declarator, IdentifierSyntax identifier, string documentation, DefinitionKind kind, Scope scope)
            : base(documentation, kind, scope, identifier.Span)
        {
            if (kind == DefinitionKind.LocalVariable)
            {
                this.Name = ColoredString.Create(identifier.Identifier, ColorType.LocalVariable);
            }
            else
            {
                this.Name = ColoredString.Create(identifier.Identifier, ColorType.GlobalVariable);
            }

            InterfaceBlockSyntax block = declarator.Parent as InterfaceBlockSyntax;

            this.TypeQualifiers = block.TypeQualifier?.ToSyntaxTypes() ?? new List <SyntaxType>();
            this.Type           = new TypeDefinition(SyntaxType.TypeName);

            List <ColoredString> arraySpecifiers = new List <ColoredString>();

            for (int i = 0; i < declarator.ArraySpecifiers.Count; i++)
            {
                arraySpecifiers.AddRange(declarator.ArraySpecifiers[i].ToColoredString());
            }

            this.ArraySpecifiers = arraySpecifiers;
        }
Exemplo n.º 18
0
        public override void Render()
        {
            if (DropMode)
            {
                this.Title = "Inventory - DropMode";
            }
            else
            {
                this.Title = "Inventory";
            }
            if (inventory != null)
            {
                this.VirtualCursor.Position = new Point(0, 1);
                foreach (var item in inventory.inventory)
                {
                    this.VirtualCursor.Down(1);
                    this.VirtualCursor.Right(1);
                    var           s   = char.ConvertFromUtf32(item.Value.GetComponent <SpriteAnimation>(ComponentType.SpriteAnimation).Symbol);
                    ColoredString str = new ColoredString("");
                    str += string.Format("{0}:", item.Key).CreateColored(Color.White);
                    if (inventoryUser.GetComponent <Equipment>(ComponentType.Equipment).Contains(item.Value.GetComponent <Item>(ComponentType.Item)))
                    {
                        str += "(E)".CreateColored(Color.Crimson);
                        str += ":".CreateColored(Color.White);
                    }
                    str += new ColoredString(s, item.Value.GetComponent <SpriteAnimation>(ComponentType.SpriteAnimation).Foreground, item.Value.GetComponent <SpriteAnimation>(ComponentType.SpriteAnimation).Background);
                    str += string.Format(":{0}", item.Value.NAME).CreateColored(Color.White);

                    this.VirtualCursor.Print(str).NewLine();
                }
            }
            base.Render();
        }
Exemplo n.º 19
0
        private void PrintNoCheck(int index, ColoredString text)
        {
            int total     = index + text.Count > textSurface.Cells.Length ? textSurface.Cells.Length : index + text.Count;
            int charIndex = 0;

            for (; index < total; index++)
            {
                if (!text.IgnoreGlyph)
                {
                    textSurface.Cells[index].GlyphIndex = text[charIndex].Glyph;
                }
                if (!text.IgnoreBackground)
                {
                    textSurface.Cells[index].Background = text[charIndex].Background;
                }
                if (!text.IgnoreForeground)
                {
                    textSurface.Cells[index].Foreground = text[charIndex].Foreground;
                }
                if (!text.IgnoreSpriteEffect)
                {
                    textSurface.Cells[index].SpriteEffect = text[charIndex].SpriteEffect;
                }
                if (!text.IgnoreEffect)
                {
                    SetEffect(index, text[charIndex].Effect);
                }
                charIndex++;
            }
        }
Exemplo n.º 20
0
 public void Modify(ref ColoredString Name)
 {
     if (Armed)
     {
         Name = new ColoredString("[Armed] ", Color.Red, Color.Black) + Name;
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Shows a window prompt with two buttons for the user to click.
        /// </summary>
        /// <param name="message">The text to display. (background color is ignored)</param>
        /// <param name="yesPrompt">The yes button's text.</param>
        /// <param name="noPrompt">The no button's text.</param>
        /// <param name="resultCallback">Callback with the yes (true) or no (false) result.</param>
        public static void Prompt(ColoredString message, string yesPrompt, string noPrompt, Action <bool> resultCallback)
        {
            Window window = new Window(message.ToString().Length + 4, 6);

            message.IgnoreBackground = true;

            window.Print(2, 2, message);

            Button yesButton = new Button(yesPrompt.Length + 2);
            Button noButton  = new Button(noPrompt.Length + 2);

            yesButton.Position = new Point(2, window.textSurface.Height - 2);
            noButton.Position  = new Point(window.textSurface.Width - noButton.Width - 2, window.textSurface.Height - 2);

            yesButton.Text = yesPrompt;
            noButton.Text  = noPrompt;

            yesButton.Click += (o, e) => { window.DialogResult = true; window.Hide(); };
            noButton.Click  += (o, e) => { window.DialogResult = false; window.Hide(); };

            window.Add(yesButton);
            window.Add(noButton);

            window.Closed += (o, e) =>
            {
                resultCallback(window.DialogResult);
            };

            window.Show(true);
            window.Center();
        }
Exemplo n.º 22
0
 public FieldDefinition(IReadOnlyList <SyntaxType> typeQualifier, TypeDefinition type, string name, IReadOnlyList <ColoredString> arraySpecifiers, string documentation, Scope scope, TrackingSpan span)
     : base(ColoredString.Create(name, ColorType.Field), documentation, DefinitionKind.Field, scope, span)
 {
     this.TypeQualifiers  = typeQualifier ?? new List <SyntaxType>();
     this.Type            = type;
     this.ArraySpecifiers = arraySpecifiers ?? new List <ColoredString>();
 }
Exemplo n.º 23
0
        public static void Prompt(ColoredString message, string yesPrompt, string noPrompt, Action<bool> resultCallback)
        {
            Window window = new Window(message.ToString().Length + 4, 6);

            message.IgnoreBackground = true;

            window._cellData.Print(2, 2, message);

            Button yesButton = new Button(yesPrompt.Length + 2, 1);
            Button noButton = new Button(noPrompt.Length + 2, 1);

            yesButton.Position = new Microsoft.Xna.Framework.Point(2, window._cellData.Height - 2);
            noButton.Position = new Microsoft.Xna.Framework.Point(window._cellData.Width - noButton.Width - 2, window._cellData.Height - 2);

            yesButton.Text = yesPrompt;
            noButton.Text = noPrompt;

            yesButton.ButtonClicked += (o, e) => { window.DialogResult = true; window.Hide(); };
            noButton.ButtonClicked += (o, e) => { window.DialogResult = false; window.Hide(); };

            window.Add(yesButton);
            window.Add(noButton);

            window.Closed += (o, e) =>
                {
                    resultCallback(window.DialogResult);
                };

            window.Show(true);
            window.Center();
        }
Exemplo n.º 24
0
        /// <summary>
        /// Draws the string on the console at the specified location, wrapping if needed.
        /// </summary>
        /// <param name="x">X location of the text.</param>
        /// <param name="y">Y location of the text.</param>
        /// <param name="text">The string to display.</param>
        public void Print(int x, int y, string text)
        {
            if (String.IsNullOrEmpty(text))
            {
                return;
            }

            if (x >= textSurface.Width || x < 0 || y >= textSurface.Height || y < 0)
            {
                throw new Exception("X,Y is out of range for Print");
            }

            int index = y * textSurface.Width + x;

            if (!UsePrintProcessor)
            {
                int total     = index + text.Length > textSurface.Cells.Length ? textSurface.Cells.Length - index : index + text.Length;
                int charIndex = 0;
                for (; index < total; index++)
                {
                    textSurface.Cells[index].Glyph = text[charIndex];
                    charIndex++;
                }
            }
            else
            {
                PrintNoCheck(index, ColoredString.Parse(text, index, textSurface, this));
            }

            textSurface.IsDirty = true;
        }
Exemplo n.º 25
0
        public ColoredString ColoredSeason()
        {
            Color SeasonColor = new Color();

            switch (GetSeasonName())
            {
            case "Spring":
                SeasonColor = Color.SpringGreen;
                break;

            case "Summer":
                SeasonColor = Color.Goldenrod;
                break;

            case "Autumn":
                SeasonColor = Color.OrangeRed;
                break;

            case "Winter":
                SeasonColor = Color.CornflowerBlue;
                break;

            default:
                SeasonColor = Color.Red;
                break;
            }

            var           date   = GetSeasonName() + " ";
            ColoredString season = new ColoredString(date, SeasonColor, Color.TransparentBlack);

            return(season);
        }
Exemplo n.º 26
0
        public ParseCommandGradient(string parameters)
        {
            var badCommandException = new ArgumentException("command is invalid for Recolor: " + parameters);

            string[] parametersArray = parameters.Split(':');

            if (parametersArray.Length > 3)
            {
                CommandType = parametersArray[0] == "b" ? CommandTypes.Background : CommandTypes.Foreground;
                Counter = Length = int.Parse(parametersArray[parametersArray.Length - 1]);

                bool keep;
                bool useDefault;

                List<Color> steps = new List<Color>();

                for (int i = 1; i < parametersArray.Length - 1; i++)
                {
                    steps.Add(Color.White.FromParser(parametersArray[i], out keep, out keep, out keep, out keep, out useDefault));
                }

                GradientString = new ColorGradient(steps.ToArray()).ToColoredString(new string(' ', Length));
            }

            else
                throw badCommandException;
        }
Exemplo n.º 27
0
 public ParameterDefinition(IReadOnlyList <SyntaxType> typeQualifier, TypeDefinition type, string identifier, string documentation, IReadOnlyList <ColoredString> arraySpecifiers, Scope scope, TrackingSpan span)
     : base(ColoredString.Create(identifier, ColorType.Parameter), documentation, DefinitionKind.Parameter, scope, span)
 {
     this.TypeQualifiers  = typeQualifier ?? new List <SyntaxType>();
     this.Type            = type;
     this.ArraySpecifiers = arraySpecifiers ?? new List <ColoredString>();
 }
Exemplo n.º 28
0
        public override IReadOnlyList <ColoredString> GetColoredText()
        {
            List <ColoredString> list = new List <ColoredString>();

            list.AddRange(this.ReturnType.GetColoredText());

            list.Add(ColoredString.Space);

            list.Add(this.Name);

            list.Add(ColoredString.Create("(", ColorType.Punctuation));

            for (int i = 0; i < this.Parameters.Count; i++)
            {
                if (i != 0)
                {
                    list.Add(ColoredString.Create(",", ColorType.Punctuation));
                    list.Add(ColoredString.Space);
                }

                list.AddRange(this.Parameters[i].GetColoredText());
            }

            list.Add(ColoredString.Create(")", ColorType.Punctuation));

            return(list);
        }
Exemplo n.º 29
0
        // Removes an Actor that has died
        // and displays a message showing
        // the actor that has died, and they loot they dropped
        private static void ResolveDeath(Actor actor)
        {
            // Set up a customized death message
            ColoredString deathMessage = new ColoredString($"{actor.Name} has died");

            // dump the dead actor's inventory (if any)
            // at the map position where it died
            if (actor.Inventory.Count > 0)
            {
                deathMessage.String += (" and dropped");

                foreach (Item item in actor.Inventory)
                {
                    // move the Item to the place where the actor died
                    item.Position = actor.Position;

                    // Now let the MultiSpatialMap know that the Item is visible

                    GameLoop.World.CurrentMap.Add(item);

                    // Append the item to the deathMessage
                    deathMessage.String += (", " + item.Name);
                }

                // Clear the actor's inventory. Not strictly
                // necessary, but makes for good coding habits!
                actor.Inventory.Clear();
            }
            else
            {
                // The monster carries no loot, so don't show any loot dropped
                deathMessage.String += (".");
            }

            // actor goes bye-bye
            GameLoop.World.CurrentMap.Remove(actor);

            // Now show the deathMessage in the messagelog
            GameLoop.UIManager.MessageLog.Add(deathMessage);


            if (actor is Player)
            {
                ColoredString message = new ColoredString($" {actor.Name} was killed.");
                GameLoop.UIManager.MessageLog.Add(message);
            }
            else if (actor is Monster)
            {
                ColoredString message = new ColoredString($"{actor.Name} died and dropped {actor.Gold} gold coins.");
                GameLoop.UIManager.MessageLog.Add(message);

                //Update the player stats and call the refresh function to draw them
                GameLoop.World.Player.Gold += actor.Gold;

                var stat = new ColoredString($"Gold: {GameLoop.World.Player.Gold}", Color.Gold, Color.Transparent);
                GameLoop.UIManager.StatWindow._lines[5] = stat;
                GameLoop.UIManager.StatWindow.Refresh();
            }
        }
Exemplo n.º 30
0
 public void Write(ColoredString message)
 {
     _lines.Enqueue(message.ToString());
     if (_fireNewMessage != null)
     {
         _fireNewMessage(this, new NewMessageEventArgs(message));
     }
 }
Exemplo n.º 31
0
        public void ImplicitStringifyingWorks()
        {
            var s = new ColoredString("text", ConsoleColor.Blue);

            string str = s;

            str.Should().Be("text");
        }
    public static void PrintColor(ColoredString str)
    {
        var prevColor = Console.BackgroundColor;

        Console.BackgroundColor = str.Color;
        Console.Write(str.Content);
        Console.BackgroundColor = prevColor;
    }
Exemplo n.º 33
0
        /// <summary>
        /// Displays a dialog to the user with a specific message.
        /// </summary>
        /// <param name="message">The message. (background color is ignored)</param>
        /// <param name="closeButtonText">The text of the dialog's close button.</param>
        /// <param name="closedCallback">A callback indicating the message was dismissed.</param>
        public static void Message(ColoredString message, string closeButtonText, Action closedCallback = null)
        {
            Window window = new Window(message.ToString().Length + 4, 6);

            message.IgnoreBackground = true;

            window.Print(2, 2, message);

            Button closeButton = new Button(closeButtonText.Length + 2);

            closeButton.Position = new Point(2, window.textSurface.Height - 2);

            closeButton.Text = closeButtonText;

            closeButton.Click += (o, e) => { window.DialogResult = true; window.Hide(); closedCallback?.Invoke(); };

            window.Add(closeButton);

            window.Show(true);
            window.Center();
        }
Exemplo n.º 34
0
        public static void Message(ColoredString message, string closeButtonText)
        {
            Window window = new Window(message.ToString().Length + 4, 6);

            message.IgnoreBackground = true;

            window._cellData.Print(2, 2, message);

            Button closeButton = new Button(closeButtonText.Length + 2, 1);

            closeButton.Position = new Microsoft.Xna.Framework.Point(2, window._cellData.Height - 2);

            closeButton.Text = closeButtonText;

            closeButton.ButtonClicked += (o, e) => { window.DialogResult = true; window.Hide(); };

            window.Add(closeButton);

            window.Show(true);
            window.Center();
        }
Exemplo n.º 35
0
        private void PrintNoCheck(int index, ColoredString text)
        {
            int total = index + text.Count > textSurface.Cells.Length ? textSurface.Cells.Length : index + text.Count;
            int charIndex = 0;

            for (; index < total; index++)
            {
                if (!text.IgnoreGlyph)
                    textSurface.Cells[index].GlyphIndex = text[charIndex].Glyph;
                if (!text.IgnoreBackground)
                    textSurface.Cells[index].Background = text[charIndex].Background;
                if (!text.IgnoreForeground)
                    textSurface.Cells[index].Foreground = text[charIndex].Foreground;
                if (!text.IgnoreSpriteEffect)
                    textSurface.Cells[index].SpriteEffect = text[charIndex].SpriteEffect;
                if (!text.IgnoreEffect)
                    SetEffect(index, text[charIndex].Effect);
                charIndex++;
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Draws the string on the console at the specified location, wrapping if needed.
        /// </summary>
        /// <param name="x">X location of the text.</param>
        /// <param name="y">Y location of the text.</param>
        /// <param name="text">The string to display.</param>
        public void Print(int x, int y, ColoredString text)
        {
            if (x >= textSurface.Width || x < 0 || y >= textSurface.Height || y < 0)
                throw new Exception("X,Y is out of range for Print");

            int index = y * textSurface.Width + x;
            PrintNoCheck(index, text);
        }
Exemplo n.º 37
0
        /// <summary>
        /// Prints text to the console using the appearance of the colored string.
        /// </summary>
        /// <param name="text">The text to print.</param>
        /// <returns>Returns this cursor object.</returns>
        public Cursor Print(ColoredString text)
        {
            // If we don't want the pretty print, or we're printing a single character (for example, from keyboard input)
            // Then use the pretty print system.
            if (!DisableWordBreak && text.String.Length != 1)
            {
                // Prep
                var console = (SurfaceEditor)_console.Target;
                ColoredGlyph glyph;
                ColoredGlyph spaceGlyph = text[0].Clone();
                spaceGlyph.Glyph = ' ';
                string stringText = text.String.TrimEnd(' ');

                // Pull any starting spaces off
                var newStringText = stringText.TrimStart(' ');
                int spaceCount = stringText.Length - newStringText.Length;

                for (int i = 0; i < spaceCount; i++)
                    PrintGlyph(spaceGlyph, text);

                if (spaceCount != 0)
                    text = text.SubString(spaceCount, text.Count - spaceCount);

                stringText = newStringText;
                string[] parts = stringText.Split(' ');

                // Start processing the string
                int c = 0;

                for (int wordMajor = 0; wordMajor < parts.Length; wordMajor++)
                {
                    // Words broken up by spaces = parts
                    if (parts[wordMajor].Length != 0)
                    {
                        // Parts broken by new lines = newLineParts
                        string[] newlineParts = parts[wordMajor].Split('\n');

                        for (int indexNL = 0; indexNL < newlineParts.Length; indexNL++)
                        {
                            if (newlineParts[indexNL].Length != 0)
                            {
                                int currentLine = _position.Y;

                                // New line parts broken up by carriage returns = returnParts
                                string[] returnParts = newlineParts[indexNL].Split('\r');

                                for (int indexR = 0; indexR < returnParts.Length; indexR++)
                                {
                                    // If the text we'll print will move off the edge, fill with spaces to get a fresh line
                                    if (returnParts[indexR].Length > console.Width - _position.X && _position.X != 0)
                                    {
                                        var spaces = console.Width - _position.X;

                                        // Fill rest of line with spaces
                                        for (int i = 0; i < spaces; i++)
                                            PrintGlyph(spaceGlyph, text);
                                    }

                                    // Print the rest of the text as normal.
                                    for (int i = 0; i < returnParts[indexR].Length; i++)
                                    {
                                        glyph = text[c];

                                        PrintGlyph(glyph, text);

                                        c++;
                                    }

                                    // If we had a \r in the string, handle it by going back
                                    if (returnParts.Length != 1 && indexR != returnParts.Length - 1)
                                    {
                                        // Wrapped to a new line through print glyph, which triggerd \r\n. We don't want the \n so return back.
                                        if (_position.X == 0 && _position.Y != currentLine)
                                            _position.Y -= 1;
                                        else
                                            CarriageReturn();
                                        c++;
                                    }
                                }
                            }

                            // We had \n in the string, handle them.
                            if (newlineParts.Length != 1 && indexNL != newlineParts.Length - 1)
                            {
                                if (!UseLinuxLineEndings)
                                    LineFeed();
                                else
                                    NewLine();
                                c++;
                            }
                        }
                    }

                    // Not last part
                    if (wordMajor != parts.Length - 1 && _position.X != 0)
                    {
                        PrintGlyph(spaceGlyph, text);
                        c++;
                    }
                    else
                        c++;
                }
            }
            else
            {
                bool movedLines = false;
                int oldLine = _position.Y;

                foreach (var glyph in text)
                {
                    // Check if the previous print moved us down a line (from print at end of the line) and move use back for the \r
                    if (movedLines)
                    {
                        if (_position.X == 0 && glyph.Glyph == '\r')
                        {
                            _position.Y -= 1;
                            continue;
                        }
                        else
                            movedLines = false;
                    }

                    if (glyph.Glyph == '\r')
                        CarriageReturn();

                    else if (glyph.Glyph == '\n')
                    {
                        if (!UseLinuxLineEndings)
                            LineFeed();
                        else
                            NewLine();
                    }
                    else
                    {
                        PrintGlyph(glyph, text);

                        // Lines changed and it wasn't a \n that caused it, so it was a print that did it.
                        movedLines = _position.Y != oldLine;
                    }
                }
            }
            return this;
        }
Exemplo n.º 38
0
        private void PrintGlyph(ColoredGlyph glyph, ColoredString settings)
        {
            var console = (SurfaceEditor)_console.Target;
            var cell = console.TextSurface.Cells[_position.Y * console.TextSurface.Width + _position.X];

            if (!PrintOnlyCharacterData)
            {
                if (!settings.IgnoreBackground)
                    cell.Background = glyph.Background;
                if (!settings.IgnoreForeground)
                    cell.Foreground = glyph.Foreground;
                if (!settings.IgnoreEffect)
                    cell.Effect = glyph.Effect;
                if (!settings.IgnoreSpriteEffect)
                    cell.SpriteEffect = glyph.SpriteEffect;
            }

            if (!settings.IgnoreGlyph)
                cell.GlyphIndex = glyph.Glyph;

            _position.X += 1;
            if (_position.X >= console.TextSurface.Width)
            {
                _position.X = 0;
                _position.Y += 1;

                if (_position.Y >= console.TextSurface.Height)
                {
                    _position.Y -= 1;

                    if (AutomaticallyShiftRowsUp)
                    {
                        console.ShiftUp();
                    }
                }
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Builds a string from the text surface.
        /// </summary>
        /// <param name="index">Where to start getting characters from.</param>
        /// <param name="length">How many characters to fill the string with.</param>
        /// <returns>A string built from the text surface data.</returns>
        public ColoredString GetStringColored(int index, int length)
        {
            if (index >= 0 && index < textSurface.Cells.Length)
            {
                ColoredString sb = new ColoredString(length);

                int tempIndex = 0;
                for (int i = 0; i < length; i++)
                {
                    tempIndex = i + index;

                    if (tempIndex < textSurface.Cells.Length)
                        textSurface.Cells[tempIndex].CopyAppearanceTo(sb[i]);
                }

                return sb;
            }

            return new ColoredString(string.Empty);
        }
Exemplo n.º 40
0
            /// <summary>
            /// Prints text to the console using the appearance of the colored string.
            /// </summary>
            /// <param name="text">The text to print.</param>
            /// <returns>Returns this cursor object.</returns>
            public Cursor Print(ColoredString text)
            {
                var console = (Console)_console.Target;

                foreach (var character in text)
                {
                    if (character.Character == '\r')
                        CarriageReturn();

                    else if (character.Character == '\n')
                        LineFeed();

                    else
                    {
                        var cell = console.CellData[_position.X, _position.Y];

                        if (!PrintOnlyCharacterData)
                        {
                            if (!text.IgnoreCharacter)
                                cell.CharacterIndex = character.Character;
                            if (!text.IgnoreBackground)
                                cell.Background = character.Background;
                            if (!text.IgnoreForeground)
                                cell.Foreground = character.Foreground;
                            if (!text.IgnoreEffect)
                                console._cellData.SetEffect(cell, character.Effect);
                        }

                        _position.X += 1;
                        if (_position.X > console.CellData.Width - 1)
                        {
                            _position.X = 0;
                            _position.Y += 1;

                            if (_position.Y > console.CellData.Height - 1)
                            {
                                _position.Y -= 1;

                                if (AutomaticallyShiftRowsUp)
                                    console.CellData.ShiftRowsUp();
                            }
                        }
                    }
                }

                return this;
            }