コード例 #1
0
ファイル: Culture.cs プロジェクト: dragontamer8740/Noxico
        static Culture()
        {
            Program.WriteLine("Loading cultures...");
            Cultures = new Dictionary <string, Culture>();
            NameGens = new Dictionary <string, Token>();
            var cultures = Mix.GetTokenTree("culture.tml");

            foreach (var c in cultures.Where(t => t.Name == "culture"))
            {
                Cultures.Add(c.Text, Culture.FromToken(c));
            }
            DefaultCulture = Cultures.ElementAt(0).Value;
            foreach (var c in cultures.Where(t => t.Name == "namegen"))
            {
                NameGens.Add(c.Text, c);
            }
            DefaultNameGen = NameGens.ElementAt(0).Value;
        }
コード例 #2
0
ファイル: Editor.cs プロジェクト: dragontamer8740/Noxico
        public ColorEditorControl(Color value)
        {
            Value = value;

            hexField  = new TextBox();
            knownList = new ListBox();

            hexField.Text = value.ToHex();
            hexField.Dock = DockStyle.Top;

            if (colors == null)
            {
                colors = new List <Tuple <string, SolidBrush> >();
                var knownColors = Mix.GetTokenTree("knowncolors.tml", true);
                foreach (var knownColor in knownColors)
                {
                    var name  = knownColor.Name;
                    var brush = new SolidBrush(System.Drawing.Color.FromArgb((int)((long)knownColor.Value | 0xFF000000)));
                    colors.Add(new Tuple <string, SolidBrush>(name, brush));
                }
            }
            knownList.Items.AddRange(colors.ToArray());

            for (var i = 0; i < colors.Count; i++)
            {
                var colorHere = colors[i].Item2.Color.ToArgb();
                if ((colorHere & 0xFFFFFF) == (value.ArgbValue & 0xFFFFFF))
                {
                    knownList.SelectedIndex = i;
                    break;
                }
            }

            knownList.DrawMode              = DrawMode.OwnerDrawFixed;
            knownList.DrawItem             += new DrawItemEventHandler(knownList_DrawItem);
            knownList.SelectedIndexChanged += new EventHandler(knownList_SelectedIndexChanged);
            knownList.Dock = DockStyle.Fill;

            Controls.Add(knownList);
            Controls.Add(hexField);
        }
コード例 #3
0
        public static void LoadBiomes()
        {
            Biomes      = new List <BiomeData>();
            WaterLevels = new List <int>();
            WaterTypes  = new List <Fluids>();
            var biomeData = Mix.GetTokenTree("biomes.tml");
            var i         = 0;

            foreach (var realm in biomeData.Where(x => x.Name == "realm"))
            {
                var waterLevel = (int)realm.GetToken("waterlevel").Value;
                WaterLevels.Add(waterLevel);
                var waterType = (Fluids)Enum.Parse(typeof(Fluids), realm.GetToken("watertype").Text, true);
                WaterTypes.Add(waterType);
                foreach (var biome in realm.Tokens.Where(x => x.Name == "biome"))
                {
                    Biomes.Add(BiomeData.FromToken(biome, i));
                }
                i++;
            }
        }
コード例 #4
0
        public static void Handler()
        {
            var host = NoxicoGame.HostForm;

            if (Subscreens.FirstDraw)
            {
                UIManager.Initialize();
                Subscreens.FirstDraw = false;
                NoxicoGame.ClearKeys();
                Subscreens.Redraw = true;

                var backdrop = new Bitmap(Program.Cols, Program.Rows * 2, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                var ccback   = Mix.GetBitmap("travelback.png");
                var ccpage   = Mix.GetBitmap("ccpage.png");
                var ccbars   = Mix.GetBitmap("ccbars.png");
                var pageTop  = Program.Rows - (ccpage.Height / 2);
                using (var gfx = Graphics.FromImage(backdrop))
                {
                    gfx.Clear(Color.Black);
                    gfx.DrawImage(ccback, 0, 0, Program.Cols, Program.Rows * 2);
                    gfx.DrawImage(ccpage, 0, pageTop, ccpage.Width, ccpage.Height);
                    var barsSrc = new System.Drawing.Rectangle(0, 3, ccbars.Width, 7);
                    var barsDst = new System.Drawing.Rectangle(0, 0, Program.Cols, 7);
                    gfx.DrawImage(ccbars, barsDst, barsSrc, GraphicsUnit.Pixel);
                    barsSrc = new System.Drawing.Rectangle(0, 0, ccbars.Width, 5);
                    barsDst = new System.Drawing.Rectangle(0, (Program.Rows * 2) - 5, Program.Cols, 5);
                    gfx.DrawImage(ccbars, barsDst, barsSrc, GraphicsUnit.Pixel);
                }

                var list = new UIList()
                {
                    Left       = 4,
                    Top        = (pageTop / 2) + 4,
                    Width      = 34,
                    Height     = (ccpage.Height / 2) - 6,
                    Background = Color.White,
                    Foreground = Color.Black,
                };

                UIManager.Elements.Add(new UIPNGBackground(backdrop));
                UIManager.Elements.Add(new UILabel(i18n.GetString("travel_header"))
                {
                    Left = 1, Top = 0, Foreground = Color.Silver
                });
                UIManager.Elements.Add(new UILabel(i18n.GetString("travel_footer"))
                {
                    Left = 1, Top = Program.Rows - 1, Foreground = Color.Silver
                });
                UIManager.Elements.Add(new UILabel(i18n.GetString("travel_current") + "\n \x07<cCyan> " + (host.Noxico.CurrentBoard.Name ?? "Somewhere"))
                {
                    Left       = 44,
                    Top        = (pageTop / 2) + 4,
                    Width      = Program.Cols - 46,
                    Foreground = Color.Teal
                });
                UIManager.Elements.Add(list);

                var targets = new List <int>();
                foreach (var target in NoxicoGame.TravelTargets)
                {
                    targets.Add(target.Key);
                }
                targets.Sort();
                list.Items.AddRange(targets.Select(x => NoxicoGame.TravelTargets[x]));
                list.Index = 0;                 //fixes crash when pressing Enter right away

                list.Enter = (s, e) =>
                {
                    var newBoard = NoxicoGame.TravelTargets.First(tn => tn.Value == list.Text).Key;
                    if (host.Noxico.CurrentBoard.BoardNum == newBoard)
                    {
                        return;
                    }

                    NoxicoGame.Mode      = UserMode.Walkabout;
                    Subscreens.FirstDraw = true;

                    NoxicoGame.InGameTime = NoxicoGame.InGameTime.AddDays(1);
                    while (Toolkit.IsNight())
                    {
                        NoxicoGame.InGameTime = NoxicoGame.InGameTime.AddHours(Random.Next(1, 3));
                    }
                    NoxicoGame.InGameTime = NoxicoGame.InGameTime.AddMinutes(Random.Next(10, 50));

                    host.Noxico.Player.OpenBoard(newBoard);
                    var hereNow = host.Noxico.Player.ParentBoard;
                    if (hereNow.BoardType == BoardType.Dungeon)
                    {
                        //find the exit and place the player there
                        //TODO: something similar for towns
                        var dngExit = hereNow.Warps.FirstOrDefault(w => w.TargetBoard == -2);
                        if (dngExit != null)
                        {
                            host.Noxico.Player.XPosition = dngExit.XPosition;
                            host.Noxico.Player.YPosition = dngExit.YPosition;
                        }
                    }
                    else
                    {
                        host.Noxico.Player.Reposition();
                    }
                };

                if (host.Noxico.CurrentBoard.Name != null)
                {
                    var thisBoard = NoxicoGame.TravelTargets.FirstOrDefault(tn => host.Noxico.CurrentBoard.Name.StartsWith(tn.Value));
                    if (thisBoard.Value != null)
                    {
                        list.Index = list.Items.FindIndex(i => thisBoard.Value.StartsWith(i));
                    }
                }
            }
            if (Subscreens.Redraw)
            {
                Subscreens.Redraw = false;
                UIManager.Draw();
            }

            if (NoxicoGame.IsKeyDown(KeyBinding.Back) || Vista.Triggers == XInputButtons.B)
            {
                NoxicoGame.ClearKeys();
                NoxicoGame.Immediate = true;
                host.Noxico.CurrentBoard.Redraw();
                host.Noxico.CurrentBoard.Draw(true);
                host.Noxico.CurrentBoard.AimCamera();
                NoxicoGame.Mode      = UserMode.Walkabout;
                Subscreens.FirstDraw = true;
            }
            else
            {
                UIManager.CheckKeys();
            }
        }
コード例 #5
0
ファイル: Introduction.cs プロジェクト: klorpa/Noxico
        private static Bitmap backdrop;                   //, backWithPortrait;

        /// <summary>
        /// Don't see a Subscreen with multiple handlers often...
        /// </summary>
        public static void CharacterCreator()
        {
            if (Subscreens.FirstDraw)
            {
                //Start creating the world as we work...
                if (worldgen == null)                 //Conditional added by Mat.
                {
                    worldgen = new System.Threading.Thread(NoxicoGame.Me.CreateRealm);
                    worldgen.Start();
                }

                //Load all bonus traits.
                var traits     = new List <string>();
                var traitHelps = new List <string>();
                var traitsDoc  = Mix.GetTokenTree("bonustraits.tml");
                foreach (var trait in traitsDoc.Where(t => t.Name == "trait"))
                {
                    traits.Add(trait.GetToken("display").Text);
                    traitHelps.Add(trait.GetToken("description").Text);
                }
                //Define the help texts for the standard controls.
                controlHelps = new Dictionary <string, string>()
                {
                    { "back", i18n.GetString("cchelp_back") },
                    { "next", i18n.GetString("cchelp_next") },
                    { "play", Random.NextDouble() > 0.7 ? "FRUITY ANGELS MOLEST SHARKY" : "ENGAGE RIDLEY MOTHER F****R" },
                    { "name", i18n.GetString("cchelp_name") },
                    { "species", string.Empty },
                    { "sex", i18n.GetString("cchelp_sex") },
                    { "gid", i18n.GetString("cchelp_gid") },
                    { "pref", i18n.GetString("cchelp_pref") },
                    { "tutorial", i18n.GetString("cchelp_tutorial") },
                    { "easy", i18n.GetString("cchelp_easy") },
                    { "gift", traitHelps[0] },
                };

                var xScale = Program.Cols / 80f;
                var yScale = Program.Rows / 25f;

                //backdrop = Mix.GetBitmap("chargen.png");
                backdrop = new Bitmap(Program.Cols, Program.Rows * 2, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                var ccback   = Mix.GetBitmap("ccback.png");
                var ccpage   = Mix.GetBitmap("ccpage.png");
                var ccbars   = Mix.GetBitmap("ccbars.png");
                var pageLeft = Program.Cols - ccpage.Width - (int)(2 * yScale);
                var pageTop  = Program.Rows - (ccpage.Height / 2);
                using (var gfx = Graphics.FromImage(backdrop))
                {
                    gfx.Clear(Color.Black);
                    gfx.DrawImage(ccback, 0, 0, Program.Cols, Program.Rows * 2);
                    gfx.DrawImage(ccpage, pageLeft, pageTop, ccpage.Width, ccpage.Height);
                    var barsSrc = new System.Drawing.Rectangle(0, 3, ccbars.Width, 7);
                    var barsDst = new System.Drawing.Rectangle(0, 0, Program.Cols, 7);
                    gfx.DrawImage(ccbars, barsDst, barsSrc, GraphicsUnit.Pixel);
                    barsSrc = new System.Drawing.Rectangle(0, 0, ccbars.Width, 5);
                    barsDst = new System.Drawing.Rectangle(0, (Program.Rows * 2) - 5, Program.Cols, 5);
                    gfx.DrawImage(ccbars, barsDst, barsSrc, GraphicsUnit.Pixel);
                }

                //Build the interface.
                var      title       = "\xB4 " + i18n.GetString("cc_title") + " \xC3";
                var      bar         = new string('\xC4', 33);
                string[] sexoptions  = { i18n.GetString("Male"), i18n.GetString("Female"), i18n.GetString("Herm"), i18n.GetString("Neuter") };
                string[] prefoptions = { i18n.GetString("Male"), i18n.GetString("Female"), i18n.GetString("Either") };

                var labelL  = pageLeft + 5;
                var cntrlL  = labelL + 2;
                var header  = (pageTop / 2) + 3;
                var top     = header + 2;
                var buttons = (pageTop / 2) + 20;

                controls = new Dictionary <string, UIElement>()
                {
                    { "backdrop", new UIPNGBackground(backdrop) },                     //backWithPortrait) },
                    { "headerline", new UILabel(bar)
                      {
                          Left = labelL, Top = header, Foreground = Color.Black
                      } },
                    { "header", new UILabel(title)
                      {
                          Left = labelL + 17 - (title.Length() / 2), Top = header, Width = title.Length(), Foreground = Color.Black
                      } },
                    { "back", new UIButton(i18n.GetString("cc_back"), null)
                      {
                          Left = labelL, Top = buttons, Width = 10, Height = 1
                      } },
                    { "next", new UIButton(i18n.GetString("cc_next"), null)
                      {
                          Left = labelL + 23, Top = buttons, Width = 10, Height = 1
                      } },
                    { "wait", new UILabel(i18n.GetString("cc_wait"))
                      {
                          Left = labelL + 23, Top = buttons, Foreground = Color.Silver
                      } },
                    { "play", new UIButton(i18n.GetString("cc_play"), null)
                      {
                          Left = labelL + 23, Top = buttons, Width = 10, Height = 1, Hidden = true
                      } },

                    { "nameLabel", new UILabel(i18n.GetString("cc_name"))
                      {
                          Left = labelL, Top = top, Foreground = Color.Gray
                      } },
                    { "name", new UITextBox(string.Empty)
                      {
                          Left = cntrlL, Top = top + 1, Width = 24, Foreground = Color.Black, Background = Color.Transparent
                      } },
                    { "nameRandom", new UILabel(i18n.GetString("cc_random"))
                      {
                          Left = cntrlL + 2, Top = top + 1, Foreground = Color.Gray
                      } },
                    { "speciesLabel", new UILabel(i18n.GetString("cc_species"))
                      {
                          Left = labelL, Top = top + 3, Foreground = Color.Gray
                      } },
                    { "species", new UISingleList()
                      {
                          Left = cntrlL, Top = top + 4, Width = 26, Foreground = Color.Black, Background = Color.Transparent
                      } },
                    { "tutorial", new UIToggle(i18n.GetString("cc_tutorial"))
                      {
                          Left = labelL, Top = top + 6, Width = 24, Foreground = Color.Black, Background = Color.Transparent
                      } },
                    { "easy", new UIToggle(i18n.GetString("cc_easy"))
                      {
                          Left = labelL, Top = top + 7, Width = 24, Foreground = Color.Black, Background = Color.Transparent
                      } },

                    { "sexLabel", new UILabel(i18n.GetString("cc_sex"))
                      {
                          Left = labelL, Top = top, Foreground = Color.Gray
                      } },
                    { "sex", new UIRadioList(sexoptions)
                      {
                          Left = cntrlL, Top = top + 1, Width = 24, Foreground = Color.Black, Background = Color.Transparent
                      } },
                    { "gidLabel", new UILabel(i18n.GetString("cc_gid"))
                      {
                          Left = labelL, Top = top + 6, Foreground = Color.Gray
                      } },
                    { "gid", new UISingleList(string.Empty, null, sexoptions.ToList(), 0)
                      {
                          Left = cntrlL, Top = top + 7, Width = 26, Foreground = Color.Black, Background = Color.Transparent
                      } },
                    { "prefLabel", new UILabel(i18n.GetString("cc_pref"))
                      {
                          Left = labelL, Top = top + 9, Foreground = Color.Gray
                      } },
                    { "pref", new UISingleList(string.Empty, null, prefoptions.ToList(), 1)
                      {
                          Left = cntrlL, Top = top + 10, Width = 26, Foreground = Color.Black, Background = Color.Transparent
                      } },

                    { "giftLabel", new UILabel(i18n.GetString("cc_gift"))
                      {
                          Left = labelL, Top = top, Foreground = Color.Gray
                      } },
                    { "gift", new UIList(string.Empty, null, traits)
                      {
                          Left = cntrlL, Top = top + 1, Width = 30, Height = 24, Foreground = Color.Black, Background = Color.Transparent
                      } },

                    { "controlHelp", new UILabel(traitHelps[0])
                      {
                          Left = 1, Top = 1, Width = pageLeft - 2, Height = 4, Foreground = Color.White, Darken = true
                      } },
                    { "topHeader", new UILabel(i18n.GetString("cc_header"))
                      {
                          Left = 1, Top = 0, Foreground = Color.Silver
                      } },
                    { "helpLine", new UILabel(i18n.GetString("cc_footer"))
                      {
                          Left = 1, Top = Program.Rows - 1, Foreground = Color.Silver
                      } },
                };
                //Map the controls to pages.
                pages = new List <UIElement>[]
                {
                    new List <UIElement>()
                    {
                        controls["backdrop"], controls["headerline"], controls["header"], controls["topHeader"], controls["helpLine"],
                        controls["nameLabel"], controls["name"], controls["nameRandom"],
                        controls["speciesLabel"], controls["species"],
                        controls["tutorial"], controls["easy"],
                        controls["controlHelp"], controls["next"],
                    },
                    new List <UIElement>()
                    {
                        controls["backdrop"], controls["headerline"], controls["header"], controls["topHeader"], controls["helpLine"],
                        controls["sexLabel"], controls["sex"], controls["gidLabel"], controls["gid"], controls["prefLabel"], controls["pref"],
                        controls["controlHelp"], controls["back"], controls["next"],
                    },
                    new List <UIElement>(),                    //Placeholder, filled in on-demand from PlayableRace.ColorItems.
                    new List <UIElement>()
                    {
                        controls["backdrop"], controls["headerline"], controls["header"], controls["topHeader"], controls["helpLine"],
                        controls["giftLabel"], controls["gift"],
                        controls["controlHelp"], controls["back"], controls["wait"], controls["play"],
                    },
                };

                CollectPlayables();

                loadPage = new Action <int>(p =>
                {
                    UIManager.Elements.Clear();
                    UIManager.Elements.AddRange(pages[page]);
                    UIManager.Highlight = UIManager.Elements[5];                     //select whatever comes after helpLine.
                });

                //Called when changing species.
                loadColors = new Action <int>(i =>
                {
                    var species             = playables[i];
                    controlHelps["species"] = species.Bestiary;
                    pages[2].Clear();
                    pages[2].AddRange(new[] { controls["backdrop"], controls["headerline"], controls["header"], controls["topHeader"], controls["helpLine"] });
                    pages[2].AddRange(species.ColorItems.Values);
                    pages[2].AddRange(new[] { controls["controlHelp"], controls["back"], controls["next"] });
                });

                controls["back"].Enter = (s, e) => { page--; loadPage(page); UIManager.Draw(); };
                controls["next"].Enter = (s, e) => { page++; loadPage(page); UIManager.Draw(); };
                controls["play"].Enter = (s, e) =>
                {
                    var playerName = controls["name"].Text;
                    var sex        = ((UIRadioList)controls["sex"]).Value;
                    var gid        = ((UISingleList)controls["gid"]).Index;
                    var pref       = ((UISingleList)controls["pref"]).Index;
                    var species    = ((UISingleList)controls["species"]).Index;
                    var tutorial   = ((UIToggle)controls["tutorial"]).Checked;
                    var easy       = ((UIToggle)controls["easy"]).Checked;
                    var bonus      = ((UIList)controls["gift"]).Text;
                    var colorMap   = new Dictionary <string, string>();
                    foreach (var editable in playables[species].ColorItems)
                    {
                        if (editable.Key.StartsWith("lbl"))
                        {
                            continue;
                        }
                        var path  = editable.Key;
                        var value = ((UISingleList)editable.Value).Text;
                        colorMap.Add(path, value);
                    }
                    NoxicoGame.Me.CreatePlayerCharacter(playerName.Trim(), (Gender)(sex + 1), (Gender)(gid + 1), pref, playables[species].ID, colorMap, bonus);
                    if (tutorial)
                    {
                        NoxicoGame.Me.Player.Character.AddToken("tutorial");
                    }
                    if (easy)
                    {
                        NoxicoGame.Me.Player.Character.AddToken("easymode");
                    }
                    NoxicoGame.InGameTime = NoxicoGame.InGameTime.AddYears(Random.Next(0, 10));
                    NoxicoGame.InGameTime = NoxicoGame.InGameTime.AddDays(Random.Next(20, 340));
                    NoxicoGame.InGameTime = NoxicoGame.InGameTime.AddHours(Random.Next(10, 54));
                    NoxicoGame.Me.CurrentBoard.UpdateLightmap(NoxicoGame.Me.Player, true);
                    Subscreens.FirstDraw = true;
                    NoxicoGame.Immediate = true;

                    /*
                     #if DEBUG
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("orgasm_denial_ring");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("baseballbat");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("really_kinky_panties");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("timertest");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("clit_regenring");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("gExtractor");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("strapon_ovi");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("strapon");
                     #if FREETESTPOTIONS
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("foxite"); // ok
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("odd_nip"); // ok
                     * //NoxicoGame.Me.Player.Character.GetToken("items").AddToken("dogmorph"); no bodyplan
                     * //NoxicoGame.Me.Player.Character.GetToken("items").AddToken("bunnymorph"); no bodyplan
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("chaos_potion"); // ok
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("enhanced_chaos_potion"); // ok
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("demonite_potion");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("tentacle_potion");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("cock_potion");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("corrupted_cock_potion");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("neutralizer_potion");
                     * NoxicoGame.Me.Player.Character.GetToken("items").AddToken("spidermorph");
                     #endif
                     #endif
                     */
                    NoxicoGame.AddMessage(i18n.GetString("welcometonoxico"), Color.Yellow);
                    NoxicoGame.AddMessage(i18n.GetString("rememberhelp"));

                    //Story();
                };

                ((UISingleList)controls["species"]).Items.Clear();
                playables.ForEach(x => ((UISingleList)controls["species"]).Items.Add(x.Name.Titlecase()));
                ((UISingleList)controls["species"]).Index = 0;
                loadColors(0);
                ((UIRadioList)controls["sex"]).ItemsEnabled = playables[0].SexLocks;
                controls["species"].Change = (s, e) =>
                {
                    var speciesIndex = ((UISingleList)controls["species"]).Index;
                    loadColors(speciesIndex);
                    var playable = playables[speciesIndex];
                    controlHelps["species"]      = playable.Bestiary;
                    controls["controlHelp"].Text = playable.Bestiary.Wordwrap(controls["controlHelp"].Width);
                    var sexList = (UIRadioList)controls["sex"];
                    sexList.ItemsEnabled = playable.SexLocks;
                    if (!sexList.ItemsEnabled[sexList.Value])
                    {
                        //Uh-oh. Select the first non-disabled item.
                        for (var i = 0; i < sexList.ItemsEnabled.Length; i++)
                        {
                            if (sexList.ItemsEnabled[i])
                            {
                                sexList.Value = i;
                                break;
                            }
                        }
                    }
                    //redrawBackdrop(0);
                    UIManager.Draw();
                };
                controls["sex"].Change = (s, e) =>
                {
                    //redrawBackdrop(0);
                    UIManager.Draw();
                };
                controls["name"].Change = (s, e) =>
                {
                    controls["nameRandom"].Hidden = !controls["name"].Text.IsBlank();
                    UIManager.Draw();
                };
                controls["gift"].Change = (s, e) =>
                {
                    var giftIndex = ((UIList)controls["gift"]).Index;
                    controls["controlHelp"].Text = traitHelps[giftIndex].Wordwrap(controls["controlHelp"].Width);
                    controls["controlHelp"].Top  = controls["gift"].Top + giftIndex;
                    UIManager.Draw();
                };

                ((UIToggle)controls["tutorial"]).Checked = IniFile.GetValue("misc", "tutorial", true);
                ((UIToggle)controls["easy"]).Checked     = IniFile.GetValue("misc", "easymode", false);

                UIManager.Initialize();
                UIManager.HighlightChanged = (s, e) =>
                {
                    var c = controls.FirstOrDefault(x => x.Value == UIManager.Highlight);
                    if (c.Key != null && controlHelps.ContainsKey(c.Key))
                    {
                        controls["controlHelp"].Text = controlHelps[c.Key].Wordwrap(controls["controlHelp"].Width);
                        controls["controlHelp"].Top  = c.Value.Top;
                    }
                    else
                    {
                        controls["controlHelp"].Text = string.Empty;
                    }
                    UIManager.Draw();
                };
                loadPage(page);
                //redrawBackdrop(0);
                Subscreens.FirstDraw = false;
                Subscreens.Redraw    = true;
                UIManager.HighlightChanged(null, null);
                NoxicoGame.Sound.PlayMusic("set://Character Creation", false);

                NoxicoGame.InGame = false;
            }

            if (Subscreens.Redraw)
            {
                UIManager.Draw();
                Subscreens.Redraw = false;
            }

            if (WorldGenFinished)
            {
                WorldGenFinished        = false;
                controls["play"].Hidden = false;
                UIManager.Draw();
            }

            UIManager.CheckKeys();
        }
コード例 #6
0
ファイル: Cursor.cs プロジェクト: dragontamer8740/Noxico
        public override void Update()
        {
            base.Update();
            NoxicoGame.ContextMessage = i18n.GetString("context_interactmode");
            if (this.ParentBoard == null)
            {
                NoxicoGame.Mode = UserMode.Walkabout;
                return;
            }
            //this.ParentBoard.Draw(true);

            if (NoxicoGame.IsKeyDown(KeyBinding.Interact) || NoxicoGame.IsKeyDown(KeyBinding.Back) || Vista.Triggers == XInputButtons.B)
            {
                NoxicoGame.Mode = UserMode.Walkabout;
                NoxicoGame.ClearKeys();
                NoxicoGame.ContextMessage = string.Empty;
                Hide();
                return;
            }

            if (NoxicoGame.IsKeyDown(KeyBinding.TabFocus) || Vista.Triggers == XInputButtons.RightShoulder)
            {
                NoxicoGame.ClearKeys();
                Tabstop++;
                if (Tabstop >= Tabstops.Count)
                {
                    Tabstop = 0;
                }
                XPosition = Tabstops[Tabstop].X;
                YPosition = Tabstops[Tabstop].Y;
                Point();
            }

            if (NoxicoGame.IsKeyDown(KeyBinding.Accept) || Vista.Triggers == XInputButtons.A)
            {
                Subscreens.PreviousScreen.Clear();
                NoxicoGame.ClearKeys();
                var player = NoxicoGame.Me.Player;
#if DEBUG
                if (PointingAt == null)
                {
                    ActionList.Show("Debug?", this.XPosition - NoxicoGame.CameraX, this.YPosition - NoxicoGame.CameraY,
                                    new Dictionary <object, string>()
                    {
                        { "teleport", "Teleport" },
                        { "spawn", "Spawn character" },
                    },
                                    () =>
                    {
                        Hide();
                        if (ActionList.Answer is int && (int)ActionList.Answer == -1)
                        {
                            NoxicoGame.Mode = UserMode.Walkabout;
                            Hide();
                            return;
                        }
                        switch (ActionList.Answer as string)
                        {
                        case "teleport":
                            player.XPosition = this.XPosition;
                            player.YPosition = this.YPosition;
                            ParentBoard.AimCamera();
                            ParentBoard.Redraw();
                            NoxicoGame.Mode = UserMode.Aiming;
                            Point();
                            return;

                        case "spawn":
                            var spawnOptions = new Dictionary <object, string>();
                            foreach (var bp in Character.Bodyplans)
                            {
                                spawnOptions[bp.Text] = bp.Text;
                            }
                            var uniques = Mix.GetTokenTree("uniques.tml", true);
                            foreach (var bp in uniques)
                            {
                                spawnOptions['!' + bp.Text] = bp.Text;
                            }
                            ActionList.Show("Debug?", this.XPosition - NoxicoGame.CameraX, this.YPosition - NoxicoGame.CameraY, spawnOptions,
                                            () =>
                            {
                                if (ActionList.Answer is int && (int)ActionList.Answer == -1)
                                {
                                    NoxicoGame.Mode = UserMode.Aiming;
                                    Point();
                                    return;
                                }
                                Character newChar = null;
                                if (ActionList.Answer is string && ((string)ActionList.Answer).StartsWith('!'))
                                {
                                    newChar = Character.GetUnique(((string)ActionList.Answer).Substring(1));
                                }
                                else
                                {
                                    newChar = Character.Generate((string)ActionList.Answer, Gender.RollDice);
                                }
                                var newBoardChar = new BoardChar(newChar)
                                {
                                    XPosition   = this.XPosition,
                                    YPosition   = this.YPosition,
                                    ParentBoard = this.ParentBoard
                                };
                                newBoardChar.AdjustView();
                                ParentBoard.EntitiesToAdd.Add(newBoardChar);
                                ParentBoard.Redraw();
                                NoxicoGame.Mode = UserMode.Walkabout;
                                Hide();
                                return;
                            }
                                            );
                            break;
                        }
                    }
                                    );
                }
#endif
                if (PointingAt != null)
                {
                    LastTarget = PointingAt;
                    var distance = player.DistanceFrom(PointingAt);
                    var canSee   = player.CanSee(PointingAt);

                    var options     = new Dictionary <object, string>();
                    var description = "something";

                    options["look"] = i18n.GetString("action_lookatit");

                    if (PointingAt is Player)
                    {
                        description     = i18n.Format("action_descyou", player.Character.Name);
                        options["look"] = i18n.GetString("action_lookatyou");
                        if (player.Character.GetStat("excitement") >= 30)
                        {
                            options["f**k"] = i18n.GetString("action_masturbate");
                        }

                        if (player.Character.HasToken("copier") && player.Character.GetToken("copier").Value == 1)
                        {
                            if (player.Character.Path("copier/backup") != null || player.Character.Path("copier/full") == null)
                            {
                                options["revert"] = i18n.GetString("action_revert");
                            }
                        }
                    }
                    else if (PointingAt is DroppedItem)
                    {
                        var drop  = PointingAt as DroppedItem;
                        var item  = drop.Item;
                        var token = drop.Token;
                        description = item.ToString(token);
                        if (distance <= 1)
                        {
                            options["take"] = i18n.GetString("action_pickup");
                        }
                    }
                    else if (PointingAt is Container)
                    {
                        var container = PointingAt as Container;
                        description = container.Name ?? "container";
                    }
                    else if (PointingAt is Clutter)
                    {
                        var clutter = PointingAt as Clutter;
                        description = clutter.Name ?? "something";
                        if (clutter.ID == "craftstation")
                        {
                            options["craft"] = i18n.GetString("action_craft");
                        }
                    }
                    else if (PointingAt is BoardChar)
                    {
                        var boardChar = PointingAt as BoardChar;
                        description     = boardChar.Character.GetKnownName(true);
                        options["look"] = i18n.Format("action_lookathim", boardChar.Character.HimHerIt(true));

                        if (canSee && distance <= 2 && !boardChar.Character.HasToken("beast") && !boardChar.Character.HasToken("sleeping"))
                        {
                            options["talk"] = i18n.Format("action_talktohim", boardChar.Character.HimHerIt(true));
                            if (boardChar.Character.Path("role/vendor") != null && boardChar.Character.Path("role/vendor/class").Text != "carpenter")
                            {
                                options["trade"] = i18n.Format("action_trade", boardChar.Character.HimHerIt(true));
                            }
                        }

                        if (canSee && player.Character.GetStat("excitement") >= 30 && distance <= 1)
                        {
                            var mayFuck  = boardChar.Character.HasToken("willing");
                            var willRape = boardChar.Character.HasToken("helpless");

                            if (!IniFile.GetValue("misc", "allowrape", false) && willRape)
                            {
                                mayFuck = false;
                            }
                            //but DO allow it if they're helpless but willing
                            if (boardChar.Character.HasToken("willing") && willRape)
                            {
                                mayFuck  = true;
                                willRape = false;
                            }
                            if (boardChar.Character.HasToken("beast"))
                            {
                                mayFuck = false;
                            }

                            if (mayFuck)
                            {
                                options["f**k"] = i18n.Format(willRape ? "action_rapehim" : "action_fuckhim", boardChar.Character.HimHerIt(true));
                            }
                        }

                        if (canSee && !boardChar.Character.HasToken("beast") && player.Character.HasToken("copier") && player.Character.Path("copier/timeout") == null)
                        {
                            //if (player.Character.UpdateCopier())
                            if (player.Character.HasToken("fullCopy") || player.Character.HasToken("sexCopy"))
                            {
                                options["copy"] = i18n.Format("action_copyhim", boardChar.Character.HimHerIt(true));
                            }
                        }

                        if (canSee && player.Character.CanShoot() != null && player.ParentBoard.HasToken("combat"))
                        {
                            options["shoot"] = i18n.Format("action_shoothim", boardChar.Character.HimHerIt(true));
                        }
                    }

#if DEBUG
                    if (PointingAt is BoardChar)
                    {
                        options["mutate"] = "(debug) Random mutate";
                    }
                    if (PointingAt is BoardChar)
                    {
                        options["turbomutate"] = "(debug) Apply LOTS of mutations!";
                    }
#endif

                    ActionList.Show(description, PointingAt.XPosition - NoxicoGame.CameraX, PointingAt.YPosition - NoxicoGame.CameraY, options,
                                    () =>
                    {
                        Hide();
                        if (ActionList.Answer is int && (int)ActionList.Answer == -1)
                        {
                            //NoxicoGame.Messages.Add("[Aim message]");
                            NoxicoGame.Mode = UserMode.Aiming;
                            Point();
                            return;
                        }
                        switch (ActionList.Answer as string)
                        {
                        case "look":
                            if (PointingAt is DroppedItem)
                            {
                                var drop  = PointingAt as DroppedItem;
                                var item  = drop.Item;
                                var token = drop.Token;
                                var text  = (item.HasToken("description") && !token.HasToken("unidentified") ? item.GetToken("description").Text : i18n.Format("thisis_x", item.ToString(token))).Trim();
                                MessageBox.Notice(text, true);
                            }
                            else if (PointingAt is Clutter && !((Clutter)PointingAt).Description.IsBlank())
                            {
                                MessageBox.Notice(((Clutter)PointingAt).Description.Trim(), true, ((Clutter)PointingAt).Name ?? "something");
                            }
                            else if (PointingAt is Container)
                            {
                                MessageBox.Notice(((Container)PointingAt).Description.Trim(), true, ((Container)PointingAt).Name ?? "container");
                            }
                            else if (PointingAt is BoardChar)
                            {
                                if (((BoardChar)PointingAt).Character.HasToken("beast"))
                                {
                                    MessageBox.Notice(((BoardChar)PointingAt).Character.LookAt(PointingAt), true, ((BoardChar)PointingAt).Character.GetKnownName(true));
                                }
                                else
                                {
                                    TextScroller.LookAt((BoardChar)PointingAt);
                                }
                            }
                            break;

                        case "talk":
                            if (PointingAt is Player)
                            {
                                //if (Culture.CheckSummoningDay()) return;
                                if (player.Character.Path("mind").Value >= 10)
                                {
                                    MessageBox.Notice(i18n.GetString("talkingotyourself"), true);
                                }
                                else
                                {
                                    MessageBox.Notice(i18n.GetString("talkingtoyourself_nutso"), true);
                                }
                            }
                            else if (PointingAt is BoardChar)
                            {
                                var boardChar = PointingAt as BoardChar;
                                if (boardChar.Character.HasToken("hostile") && !boardChar.Character.HasToken("helpless"))
                                {
                                    MessageBox.Notice(i18n.Format("nothingtosay", boardChar.Character.GetKnownName(false, false, true, true)), true);
                                }
                                else
                                {
                                    SceneSystem.Engage(player.Character, boardChar.Character);
                                }
                            }
                            break;

                        case "trade":
                            ContainerMan.Setup(((BoardChar)PointingAt).Character);
                            break;

                        case "f**k":
                            if (PointingAt is BoardChar)
                            {
                                SexManager.Engage(player.Character, ((BoardChar)PointingAt).Character);
                            }
                            break;

                        case "shoot":
                            player.AimShot(PointingAt);
                            break;

                        case "copy":
                            player.Character.Copy(((BoardChar)PointingAt).Character);
                            player.AdjustView();
                            //NoxicoGame.AddMessage(i18n.Format((player.Character.Path("copier/full") == null) ? "youimitate_x" : "become_x", ((BoardChar)PointingAt).Character.GetKnownName(false, false, true)));
                            NoxicoGame.AddMessage(i18n.Format(player.Character.HasToken("fullCopy") ? "x_becomes_y" : "x_imitates_y").Viewpoint(player.Character, ((BoardChar)PointingAt).Character));
                            player.Energy -= 2000;
                            break;

                        case "revert":
                            player.Character.Copy(null);
                            player.AdjustView();
                            NoxicoGame.AddMessage(i18n.GetString((player.Character.HasToken("fullCopy")) ? "youmelt" : "yourevert"));
                            player.Energy -= 1000;
                            break;

                        case "take":
                            if (PointingAt is DroppedItem)
                            {
                                var drop  = PointingAt as DroppedItem;
                                var item  = drop.Item;
                                var token = drop.Token;
                                drop.Take(player.Character, ParentBoard);
                                player.Energy -= 1000;
                                NoxicoGame.AddMessage(i18n.Format("youpickup_x", item.ToString(token, true)), drop.ForegroundColor);
                                NoxicoGame.Sound.PlaySound("set://GetItem");
                                ParentBoard.Redraw();
                            }
                            break;

                        case "craft":
                            Crafting.Open(player.Character);
                            break;

#if DEBUG
                        case "edit":
                            TokenCarrier tc = null;
                            if (PointingAt is DroppedItem)
                            {
                                tc = ((DroppedItem)PointingAt).Token;
                            }
                            else if (PointingAt is BoardChar)
                            {
                                tc = ((BoardChar)PointingAt).Character;
                            }

                            NoxicoGame.HostForm.Write("TOKEN EDIT ENGAGED. Waiting for editor process to exit.", Color.Black, Color.White, 0, 0);
                            NoxicoGame.HostForm.Draw();
                            ((MainForm)NoxicoGame.HostForm).timer.Enabled = false;
                            var dump = "-- WARNING! Many things may cause strange behavior or crashes. WATCH YOUR F*****G STEP.\r\n" + tc.DumpTokens(tc.Tokens, 0);
                            var temp = Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString() + ".txt");
                            File.WriteAllText(temp, dump);
                            var process = System.Diagnostics.Process.Start(temp);
                            process.WaitForExit();
                            var newDump = File.ReadAllText(temp);
                            File.Delete(temp);
                            ((MainForm)NoxicoGame.HostForm).timer.Enabled = true;
                            ParentBoard.Redraw();
                            if (newDump == dump)
                            {
                                break;
                            }
                            tc.Tokenize(newDump);
                            ((BoardChar)PointingAt).AdjustView();
                            ((BoardChar)PointingAt).Character.RecalculateStatBonuses();
                            ((BoardChar)PointingAt).Character.CheckHasteSlow();
                            break;

                        case "mutate":
                            var result = ((BoardChar)PointingAt).Character.Mutate(1, 30);
                            NoxicoGame.AddMessage(result);
                            break;

                        case "turbomutate":
                            result = ((BoardChar)PointingAt).Character.Mutate(2500, 30);
                            NoxicoGame.AddMessage(result);
                            break;
#endif

                        default:
                            MessageBox.Notice("Unknown action handler \"" + ActionList.Answer.ToString() + "\".", true);
                            break;
                        }
                    }
                                    );             //	true, true);
                    return;
                }
                else
                {
                    /*
                     * var tSD = this.ParentBoard.GetDescription(YPosition, XPosition);
                     * if (!string.IsNullOrWhiteSpace(tSD))
                     * {
                     *      PointingAt = null;
                     *      MessageBox.ScriptPauseHandler = () =>
                     *      {
                     *              NoxicoGame.Mode = UserMode.Aiming;
                     *              Point();
                     *      };
                     *      MessageBox.Notice(tSD, true);
                     *      return;
                     * }
                     */
                }
            }

#if DEBUG
            if (NoxicoGame.KeyMap[Keys.D])
            {
                NoxicoGame.ClearKeys();
                if (PointingAt != null && PointingAt is BoardChar)
                {
                    ((BoardChar)PointingAt).Character.CreateInfoDump();
                    NoxicoGame.AddMessage("Info for " + ((BoardChar)PointingAt).Character.GetKnownName(true, true, true) + " dumped.", Color.Red);
                }
            }
#endif

            if (NoxicoGame.IsKeyDown(KeyBinding.Left) || Vista.DPad == XInputButtons.Left)
            {
                this.Move(Direction.West);
            }
            else if (NoxicoGame.IsKeyDown(KeyBinding.Right) || Vista.DPad == XInputButtons.Right)
            {
                this.Move(Direction.East);
            }
            else if (NoxicoGame.IsKeyDown(KeyBinding.Up) || Vista.DPad == XInputButtons.Up)
            {
                this.Move(Direction.North);
            }
            else if (NoxicoGame.IsKeyDown(KeyBinding.Down) || Vista.DPad == XInputButtons.Down)
            {
                this.Move(Direction.South);
            }
        }
コード例 #7
0
        public void Write(string text, Color foregroundColor, Color backgroundColor, int row = 0, int col = 0, bool darken = false)
        {
            if (!text.IsNormalized())
            {
                text = text.Normalize();
            }
            text = text.FoldEntities();

            if (fontVariants == null)
            {
                var tml = Mix.GetTokenTree("fonts\\variants.tml");
                fontVariants = new Dictionary <string, Tuple <int, bool> >();
                foreach (var t in tml)
                {
                    fontVariants.Add(t.Text, Tuple.Create((int)t.GetToken("offset").Value, t.HasToken("hasLowercase")));
                }
            }

            var font         = 0;
            var fontHasLower = true;

            var fg = foregroundColor;
            var bg = backgroundColor;
            var rx = col;

            for (var i = 0; i < text.Length; i++)
            {
                var c = text[i];
                if (c == '\r')
                {
                    continue;
                }
                if (c == '\n')
                {
                    col = rx;
                    row++;
                    continue;
                }
                if (c == '<')
                {
                    var gtPos = text.IndexOf('>', i + 1);
                    if (gtPos != -1)
                    {
                        var tag = text.Substring(i + 1);
                        i = gtPos;
                        if (tag.StartsWith("nowrap"))
                        {
                            continue;
                        }
                        if (tag[0] == 'c')
                        {
                            var match = Regex.Match(tag, @"c(?<fore>\w+)(?:,(?<back>\w+))?");
                            foregroundColor = (!string.IsNullOrEmpty(match.Groups["fore"].Value) && match.Groups["fore"].Value.Length > 1) ? Color.FromName(match.Groups["fore"].Value) : fg;
                            backgroundColor = !string.IsNullOrEmpty(match.Groups["back"].Value) ? Color.FromName(match.Groups["back"].Value) : bg;
                            continue;
                        }
                        else if (tag[0] == 'f')
                        {
                            var match = Regex.Match(tag, @"f(?<face>\w+)?");
                            font = 0;
                            var face = match.Groups["face"].Value;
                            if (!string.IsNullOrEmpty(face) && face.Length > 1)
                            {
                                if (fontVariants.ContainsKey(face))
                                {
                                    font         = fontVariants[face].Item1;
                                    fontHasLower = fontVariants[face].Item2;
                                }
                            }
                            continue;
                        }
                    }
                }
                if (font > 0)
                {
                    if (c >= 'A' && c <= 'Z')
                    {
                        c = (char)((c - 'A') + font);
                    }
                    else if (fontHasLower && c >= 'a' && c <= 'z')
                    {
                        c = (char)((c - 'a') + font + 0x1A);
                    }
                }

                if (darken)
                {
                    image[col, row].Background = image[col, row].Background.Darken();
                    image[col, row].Foreground = image[col, row].Foreground.Darken();
                }

                if (!(darken && c == ' '))
                {
                    SetCell(row, col, c, foregroundColor, backgroundColor, true);
                }
                col++;
                if ((c >= 0x3000 && c < 0x4000) || (c >= 0x4E00 && c < 0xA000) || (c >= 0xE400 && c < 0xE500))
                {
                    SetCell(row, col, '\uE2FF', Color.Black, Color.Black);
                    col++;
                }
                if (col >= Program.Cols)
                {
                    col = rx;
                    row++;
                }
                if (row >= Program.Rows)
                {
                    return;
                }
            }
        }
コード例 #8
0
        public MainForm()
        {
#if !DEBUG
            try
#endif
            {
                this.Text            = "Noxico";
                this.BackColor       = System.Drawing.Color.Black;
                this.DoubleBuffered  = true;
                this.FormBorderStyle = FormBorderStyle.FixedSingle;
                this.MaximizeBox     = false;             //it's about time, too!
                this.FormClosing    += new FormClosingEventHandler(this.Form1_FormClosing);
                this.KeyDown        += new KeyEventHandler(this.Form1_KeyDown);
                this.KeyPress       += new KeyPressEventHandler(this.Form1_KeyPress);
                this.KeyUp          += new KeyEventHandler(this.Form1_KeyUp);
                this.Icon            = global::Noxico.Properties.Resources.app;
                this.ClientSize      = new Size(Program.Cols * cellWidth, Program.Rows * cellHeight);
                this.Controls.Add(new Label()
                {
                    Text      = "Loading...",
                    AutoSize  = true,
                    Font      = new System.Drawing.Font("Arial", 24, FontStyle.Bold | FontStyle.Italic),
                    ForeColor = System.Drawing.Color.White,
                    Visible   = true,
                    Location  = new System.Drawing.Point(16, 16)
                });

                foreach (var reqDll in new[] { "Neo.Lua.dll" })
                {
                    if (!File.Exists(reqDll))
                    {
                        throw new FileNotFoundException("Required DLL " + reqDll + " is missing.");
                    }
                }

                try
                {
                    Mix.Initialize("Noxico");
                }
                catch (UnauthorizedAccessException)
                {
                    if (!UacHelper.IsProcessElevated)
                    {
                        var proc = new System.Diagnostics.ProcessStartInfo();
                        proc.UseShellExecute  = true;
                        proc.WorkingDirectory = Environment.CurrentDirectory;
                        proc.FileName         = Application.ExecutablePath;
                        proc.Verb             = "runas";
                        try
                        {
                            System.Diagnostics.Process.Start(proc);
                        }
                        catch
                        {
                        }
                    }
                    Close();
                    return;
                }

                if (!Mix.FileExists("credits.txt"))
                {
                    SystemMessageBox.Show(this, "Could not find game data. Please redownload the game.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Close();
                    return;
                }

                var portable = false;
                IniPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "noxico.ini");
                if (File.Exists("portable"))
                {
                    portable = true;
                    var oldIniPath = IniPath;
                    IniPath = "noxico.ini";
                    Program.CanWrite();

                    /*
                     * if (!Program.CanWrite())
                     * {
                     *      var response = SystemMessageBox.Show(this, "Trying to start in portable mode, but from a protected location. Use non-portable mode?" + Environment.NewLine + "Selecting \"no\" may cause errors.", Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                     *      if (response == DialogResult.Cancel)
                     *      {
                     *              Close();
                     *              return;
                     *      }
                     *      else if (response == DialogResult.Yes)
                     *      {
                     *              IniPath = oldIniPath;
                     *              portable = false;
                     *      }
                     * }
                     */
                }

                if (!File.Exists(IniPath))
                {
                    File.WriteAllText(IniPath, Mix.GetString("noxico.ini"));
                }
                IniFile.Load(IniPath);

                if (portable)
                {
                    IniFile.SetValue("misc", "vistasaves", false);
                    IniFile.SetValue("misc", "savepath", "./saves");
                    IniFile.SetValue("misc", "shotpath", "./screenshots");
                }

                RestartGraphics(true);
                fourThirtySeven = IniFile.GetValue("misc", "437", false);

                Noxico = new NoxicoGame();
                Noxico.Initialize(this);

                MouseUp    += new MouseEventHandler(MainForm_MouseUp);
                MouseWheel += new MouseEventHandler(MainForm_MouseWheel);

                GotFocus  += (s, e) => { Vista.GamepadFocused = true; };
                LostFocus += (s, e) => { Vista.GamepadFocused = false; };

                Vista.GamepadEnabled = IniFile.GetValue("misc", "xinput", true);

                Program.WriteLine("Environment: {0} {1}", Environment.OSVersion.Platform, Environment.OSVersion);
                Program.WriteLine("Application: {0}", Application.ProductVersion);
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Program.WriteLine("*** You are running on a *nix system. ***");
                    Program.WriteLine("Key repeat delays exaggerated.");
                    NoxicoGame.Mono      = true;
                    Vista.GamepadEnabled = false;
                }

                this.Controls.Clear();
                starting = false;
                Running  = true;

                Cursor           = new Point(-1, -1);
                cursorPens       = new Pen[3, 16];
                cursorPens[0, 0] = cursorPens[1, 0] = cursorPens[2, 0] = Pens.Black;
                for (var i = 1; i < 9; i++)
                {
                    cursorPens[0, i] = cursorPens[0, 16 - i] = new Pen(Color.FromArgb((i * 16) - 1, (i * 16) - 1, 0));
                    cursorPens[1, i] = cursorPens[1, 16 - i] = new Pen(Color.FromArgb(0, (i * 32) - 1, 0));
                    cursorPens[2, i] = cursorPens[2, 16 - i] = new Pen(Color.FromArgb((i * 32) - 1, (i * 32) - 1, (i * 32) - 1));
                }

                fpsTimer = new Timer()
                {
                    Interval = 1000,
                    Enabled  = true,
                };
                fpsTimer.Tick += (s, e) =>
                {
                    this.Text          = "Noxico - " + NoxicoGame.Updates + " updates, " + Frames + " frames";
                    NoxicoGame.Updates = 0;
                    Frames             = 0;
                };
#if GAMELOOP
                while (Running)
                {
                    Noxico.Update();
                    Application.DoEvents();
                }
#else
                FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
                var speed = IniFile.GetValue("misc", "speed", 15);
                if (speed <= 0)
                {
                    speed = 15;
                }
                timer = new Timer()
                {
                    Interval = speed,
                    Enabled  = true,
                };
                timer.Tick += new EventHandler(timer_Tick);
#endif
            }
#if !DEBUG
            catch (Exception x)
            {
                new ErrorForm(x).ShowDialog(this);
                SystemMessageBox.Show(this, x.ToString(), Application.ProductName, MessageBoxButtons.OK);
                Running = false;
                fatal   = true;
                Application.ExitThread();
            }
#endif
            if (!fatal)
            {
                Noxico.SaveGame();
            }
        }
コード例 #9
0
ファイル: Entities.cs プロジェクト: dragontamer8740/Noxico
        public static bool ResetToKnown(Entity thing)
        {
            if (!(thing is Clutter) && !(thing is Container))
            {
                throw new InvalidCastException("ResetToKnown only takes Clutter and Container objects.");
            }

            var name = string.Empty;

            if (thing is Clutter)
            {
                name = ((Clutter)thing).Name;
            }
            else if (thing is Container)
            {
                name = ((Container)thing).Name;
            }
            if (clutterDB == null)
            {
                clutterDB = Mix.GetTokenTree("clutter.tml", true);
            }
            var knownThing = clutterDB.FirstOrDefault(kc =>
                                                      thing.Glyph == kc.GetToken("char").Value ||
                                                      (!name.IsBlank() && name.Equals(kc.Text, StringComparison.InvariantCultureIgnoreCase)) ||
                                                      thing.ID.StartsWith(kc.Text, StringComparison.InvariantCultureIgnoreCase));

            if (knownThing != null)
            {
                thing.Glyph = (int)knownThing.GetToken("char").Value;
                if (knownThing.HasToken("color"))
                {
                    thing.ForegroundColor = Color.FromName(knownThing.GetToken("color").Text);
                    thing.BackgroundColor = thing.ForegroundColor.Darken();                     //TileDefinition.Find(parentBoardHack.Tilemap[e.XPosition, e.YPosition].Index).Background;
                }
                if (knownThing.HasToken("background"))
                {
                    if (knownThing.GetToken("background").Text == "inherit")
                    {
                        thing.BackgroundColor = TileDefinition.Find((thing.ParentBoard ?? ParentBoardHack).Tilemap[thing.XPosition, thing.YPosition].Index).Background;
                    }
                    else
                    {
                        thing.BackgroundColor = Color.FromName(knownThing.GetToken("background").Text);
                    }
                }
                if (thing is Clutter)
                {
                    ((Clutter)thing).CanBurn = knownThing.HasToken("canburn");
                }
                //else if (thing is Container) ((Container)thing).CanBurn = knownClutter.HasToken("canburn");
                thing.Blocking = knownThing.HasToken("blocking");
                if (knownThing.HasToken("description"))
                {
                    if (thing is Clutter)
                    {
                        ((Clutter)thing).Description       = knownThing.GetToken("description").Text;
                        ((Clutter)thing).descriptionFromDB = true;
                    }
                    else if (thing is Container && !((Container)thing).Token.HasToken("description"))
                    {
                        ((Container)thing).Token.AddToken("description", knownThing.GetToken("description").Text);
                    }
                }
                if (knownThing.HasToken("name"))
                {
                    if (thing is Clutter)
                    {
                        ((Clutter)thing).Name = knownThing.GetToken("name").Text;
                    }
                    if (thing is Container)
                    {
                        ((Container)thing).Name = knownThing.GetToken("name").Text;
                    }
                }
                if (knownThing.HasToken("role") && thing is Clutter)
                {
                    ((Clutter)thing).DBRole = knownThing.GetToken("role").Text;
                }
                return(true);
            }
            return(false);
        }
コード例 #10
0
ファイル: Pause.cs プロジェクト: dragontamer8740/Noxico
        public static void Handler()
        {
            var host = NoxicoGame.HostForm;

            if (Subscreens.FirstDraw)
            {
                Subscreens.FirstDraw = false;
                UIManager.Initialize();
                UIManager.Elements.Add(new UIWindow(i18n.GetString("pause_title"))
                {
                    Left = 3, Top = 1, Width = 22, Height = pages.Count + 2
                });
                UIManager.Elements.Add(new UIWindow(string.Empty)
                {
                    Left = 28, Top = 1, Width = 49, Height = 23
                });
                list = new UIList()
                {
                    Width = 20, Height = pages.Count, Left = 4, Top = 2, Background = UIColors.WindowBackground
                };
                list.Items.AddRange(pages.Keys);
                list.Change += (s, e) =>
                {
                    page      = list.Index;
                    text.Text = pages.Values.ElementAt(page);
                    UIManager.Draw();
                };
                list.Enter += (s, e) =>
                {
                    if (list.Index == list.Items.Count - 1)                     //can't use absolute index because Debug might be missing.
                    {
                        host.Close();
                    }
                    else if (list.Index == list.Items.Count - 2)                     //same
                    {
                        //System.Diagnostics.Process.Start(host.IniPath);
                        Options.Open();
                    }
                    else if (list.Index == 4)
                    {
                        TextScroller.Plain(Mix.GetString("credits.txt"), i18n.GetString("pause_credits"), false);
                    }
                };
                text = new UILabel("...")
                {
                    Left = 30, Top = 2
                };
                UIManager.Elements.Add(list);
                UIManager.Elements.Add(text);
                list.Index          = IniFile.GetValue("misc", "rememberpause", true) ? page : 0;
                UIManager.Highlight = list;

                Subscreens.Redraw = true;
            }
            if (Subscreens.Redraw)
            {
                Subscreens.Redraw = false;
                UIManager.Draw();
            }

            if (NoxicoGame.IsKeyDown(KeyBinding.Back) || Vista.Triggers == XInputButtons.B)
            {
                NoxicoGame.ClearKeys();
                NoxicoGame.Immediate = true;
                NoxicoGame.Me.CurrentBoard.Redraw();
                NoxicoGame.Me.CurrentBoard.Draw(true);
                NoxicoGame.Mode      = UserMode.Walkabout;
                Subscreens.FirstDraw = true;
            }
            else
            {
                UIManager.CheckKeys();
            }
        }
コード例 #11
0
        public static Board CreateDungeon(bool forTravel, string name)
        {
            var host = NoxicoGame.HostForm;
            var nox  = host.Noxico;

            new UIPNGBackground(Mix.GetBitmap("makecave.png")).Draw();
            host.Write("Generating dungeon. Please wait.", Color.Silver, Color.Transparent, 1, 2);
            host.Draw();

            var dunGen  = new StoneDungeonGenerator();
            var caveGen = new CaveGenerator();

            Func <Board, Warp> findWarpSpot = (b) =>
            {
                var eX       = 0;
                var eY       = 0;
                var attempts = 0;
                var minSides = 1;
                while (true)
                {
                    attempts++;
                    if (attempts == 10)
                    {
                        minSides = 0;
                    }

                    eX = Random.Next(1, b.Width - 1);
                    eY = Random.Next(1, b.Height - 1);

                    //2013-03-07: prevent placing warps on same tile as clutter
                    //<Ragath> Kawa, this is bad
                    //<Ragath> that should be a .Any() call
                    //if (b.Entities.FirstOrDefault(e => e.XPosition == eX && e.YPosition == eY) != null)
                    if (b.Entities.Any(e => e.XPosition == eX && e.YPosition == eY))
                    {
                        Program.WriteLine("Tried to place a warp below an entity -- rerolling...");
                        continue;
                    }

                    var sides = 0;
                    if (b.IsSolid(eY - 1, eX))
                    {
                        sides++;
                    }
                    if (b.IsSolid(eY + 1, eX))
                    {
                        sides++;
                    }
                    if (b.IsSolid(eY, eX - 1))
                    {
                        sides++;
                    }
                    if (b.IsSolid(eY, eX + 1))
                    {
                        sides++;
                    }
                    if (sides < 3 && sides >= minSides)
                    {
                        break;
                    }
                }
                return(new Warp()
                {
                    XPosition = eX, YPosition = eY
                });
            };

            Warp originalExit = null;

            BiomeData.LoadBiomes();
            var biomeData = BiomeData.Biomes[DungeonGeneratorBiome];

            /* Step 1 - Randomize jagged array, make boards for each entry.
             * ------------------------------------------------------------
             * ("goal" board is boss/treasure room, picked at random from bottom floor set.)
             * [EXIT] [ 01 ] [ 02 ]
             * [ 03 ] [ 04 ]
             * [ 05 ] [ 06 ] [ 07 ] [ 08 ]
             * [ 09 ] [ 10 ] [ 11 ]
             * [GOAL] [ 13 ]
             */
            var levels = new List <List <Board> >();
            var depth  = Random.Next(3, 6);

            var boardWidths  = new[] { 80, 80, 80, 40, 160, 120 };
            var boardHeights = new[] { 50, 50, 50, 25, 100, 75 };

            for (var i = 0; i < depth; i++)
            {
                levels.Add(new List <Board>());
                var length = Random.Next(2, 5);
                for (var j = 0; j < length; j++)
                {
                    var board = new Board(boardWidths.PickOne(), boardHeights.PickOne());
                    board.AllowTravel = false;
                    board.Clear(DungeonGeneratorBiome);
                    board.BoardNum   = nox.Boards.Count;
                    board.Coordinate = nox.Player.ParentBoard.Coordinate;
                    if (i > 0)
                    {
                        board.AddToken("dark");
                    }
                    nox.Boards.Add(board);
                    levels[i].Add(board);
                }
            }

            //Decide which boards are the exit and goal
            var entranceBoard = levels[0].PickOne();
            var goalBoard     = levels[levels.Count - 1].PickOne();

            //Generate content for each board
            for (var i = 0; i < levels.Count; i++)
            {
                for (var j = 0; j < levels[i].Count; j++)
                {
                    var board = levels[i][j];

                    if (Random.NextDouble() > 0.7 || board == entranceBoard)
                    {
                        caveGen.Board = board;
                        caveGen.Create(biomeData);
                        caveGen.ToTilemap(ref board.Tilemap);
                    }
                    else
                    {
                        dunGen.Board = board;
                        dunGen.Create(biomeData);
                        dunGen.ToTilemap(ref board.Tilemap);
                    }

                    board.Name = string.Format("Level {0}-{1}", i + 1, (char)('A' + j));
                    if (!name.IsBlank())
                    {
                        board.Name = string.Format("{0}, level {1}-{2}", name, i + 1, (char)('A' + j));
                    }
                    board.ID        = string.Format("Dng_{0}_{1}{2}", DungeonGeneratorEntranceBoardNum, i + 1, (char)('A' + j));
                    board.BoardType = BoardType.Dungeon;
                    board.Music     = "set://Dungeon";
                    var encounters = board.GetToken("encounters");
                    foreach (var e in biomeData.Encounters)
                    {
                        encounters.AddToken(e);
                    }
                    encounters.Value = biomeData.MaxEncounters;
                    encounters.GetToken("stock").Value = encounters.Value * Random.Next(3, 5);
                    board.RespawnEncounters();

                    //If this is the entrance board, add a warp back to the Overworld.
                    if (board == entranceBoard)
                    {
                        var exit = findWarpSpot(board);
                        originalExit = exit;
                        exit.ID      = "Dng_" + DungeonGeneratorEntranceBoardNum + "_Exit";
                        board.Warps.Add(exit);
                        board.SetTile(exit.YPosition, exit.XPosition, "dungeonExit");                         //board.SetTile(exit.YPosition, exit.XPosition, '<', Color.Silver, Color.Black);
                    }
                }
            }

            /* Step 2 - Randomly add up/down links
             * -----------------------------------
             * (imagine for the moment that each board can have more than one exit and that this goes for both directions.)
             * [EXIT] [ 01 ] [ 02 ]
             *    |
             * [ 03 ] [ 04 ]
             *           |
             * [ 05 ] [ 06 ] [ 07 ] [ 08 ]
             *    |             |
             * [ 09 ] [ 10 ] [ 11 ]
             *                  |
             *        [GOAL] [ 13 ]
             */
            var connected = new List <Board>();

            for (var i = 0; i < levels.Count; i++)
            {
                var j = Random.Next(0, levels[i].Count);
                //while (connected.Contains(levels[i][j]))
                //	j = Randomizer.Next(0, levels[i].Count);

                var up        = false;
                var destLevel = i + 1;
                if (destLevel == levels.Count)
                {
                    up        = true;
                    destLevel = i - 1;
                }
                var dest = Random.Next(0, levels[destLevel].Count);

                var boardHere  = levels[i][j];
                var boardThere = levels[destLevel][dest];

                var here  = findWarpSpot(boardHere);
                var there = findWarpSpot(boardThere);
                boardHere.Warps.Add(here);
                boardThere.Warps.Add(there);
                here.ID            = boardHere.ID + boardHere.Warps.Count;
                there.ID           = boardThere.ID + boardThere.Warps.Count;
                here.TargetBoard   = boardThere.BoardNum;
                there.TargetBoard  = boardHere.BoardNum;
                here.TargetWarpID  = there.ID;
                there.TargetWarpID = here.ID;
                boardHere.SetTile(here.YPosition, here.XPosition, up ? "dungeonUpstairs" : "dungeonDownstairs");                 //boardHere.SetTile(here.YPosition, here.XPosition, up ? '<' : '>', Color.Gray, Color.Black);
                boardThere.SetTile(there.YPosition, there.XPosition, up ? "dungeonDownstairs" : "dungeonUpstairs");              //boardThere.SetTile(there.YPosition, there.XPosition, !up ? '<' : '>', Color.Gray, Color.Black);

                Program.WriteLine("Connected {0} || {1}.", boardHere.ID, boardThere.ID);

                connected.Add(boardHere);
                connected.Add(boardThere);
            }

            /* Step 3 - Connect the Unconnected
             * --------------------------------
             * [EXIT]=[ 01 ]=[ 02 ]
             *  |
             * [ 03 ]=[ 04 ]
             *           |
             * [ 05 ]=[ 06 ] [ 07 ]=[ 08 ]
             *    |             |
             * [ 09 ]=[ 10 ]=[ 11 ]
             *                  |
             *        [GOAL]=[ 13 ]
             */

            for (var i = 0; i < levels.Count; i++)
            {
                for (var j = 0; j < levels[i].Count - 1; j++)
                {
                    //Don't connect if this board AND the right-hand neighbor are already connected.
                    //if (connected.Contains(levels[i][j]) && connected.Contains(levels[i][j + 1]))
                    //	continue;

                    var boardHere  = levels[i][j];
                    var boardThere = levels[i][j + 1];

                    var here  = findWarpSpot(boardHere);
                    var there = findWarpSpot(boardThere);
                    boardHere.Warps.Add(here);
                    boardThere.Warps.Add(there);
                    here.ID            = boardHere.ID + boardHere.Warps.Count;
                    there.ID           = boardThere.ID + boardThere.Warps.Count;
                    here.TargetBoard   = boardThere.BoardNum;
                    there.TargetBoard  = boardHere.BoardNum;
                    here.TargetWarpID  = there.ID;
                    there.TargetWarpID = here.ID;
                    boardHere.SetTile(here.YPosition, here.XPosition, "dungeonSideexit");                     //boardHere.SetTile(here.YPosition, here.XPosition, '\x2261', Color.Gray, Color.Black);
                    boardThere.SetTile(there.YPosition, there.XPosition, "dungeonSideexit");                  //boardThere.SetTile(there.YPosition, there.XPosition, '\x2261', Color.Gray, Color.Black);

                    Program.WriteLine("Connected {0} -- {1}.", boardHere.ID, boardThere.ID);

                    connected.Add(boardHere);
                    connected.Add(boardThere);
                }
            }

            // Step 4 - place sick lewt in goalBoard
            var treasureX = 0;
            var treasureY = 0;

            while (true)
            {
                treasureX = Random.Next(1, goalBoard.Width - 1);
                treasureY = Random.Next(1, goalBoard.Height - 1);

                //2013-03-07: prevent treasure from spawning inside a wall
                if (goalBoard.IsSolid(treasureY, treasureX))
                {
                    continue;
                }
                //2013-03-07: prevent placing warps on same tile as clutter
                if (goalBoard.Entities.FirstOrDefault(e => e.XPosition == treasureX && e.YPosition == treasureY) != null)
                {
                    Program.WriteLine("Tried to place cave treasure below an entity -- rerolling...");
                    continue;
                }

                var sides = 0;
                if (goalBoard.IsSolid(treasureY - 1, treasureX))
                {
                    sides++;
                }
                if (goalBoard.IsSolid(treasureY + 1, treasureX))
                {
                    sides++;
                }
                if (goalBoard.IsSolid(treasureY, treasureX - 1))
                {
                    sides++;
                }
                if (goalBoard.IsSolid(treasureY, treasureX + 1))
                {
                    sides++;
                }
                if (sides < 3 && sides > 1 && goalBoard.Warps.FirstOrDefault(w => w.XPosition == treasureX && w.YPosition == treasureY) == null)
                {
                    break;
                }
            }
            var treasure = DungeonGenerator.GetRandomLoot("container", "dungeon_chest", new Dictionary <string, string>()
            {
                { "biome", BiomeData.Biomes[DungeonGenerator.DungeonGeneratorBiome].Name.ToLowerInvariant() },
            });
            var treasureChest = new Container(i18n.GetString("treasurechest"), treasure)
            {
                Glyph           = 0x14A,
                XPosition       = treasureX,
                YPosition       = treasureY,
                ForegroundColor = Color.FromName("SaddleBrown"),
                BackgroundColor = Color.Black,
                ParentBoard     = goalBoard,
                Blocking        = false,
            };

            goalBoard.Entities.Add(treasureChest);

            if (forTravel)
            {
                originalExit.TargetBoard = -2;                 //causes Travel menu to appear on use.
                return(entranceBoard);
            }

            var entrance = nox.CurrentBoard.Warps.Find(w => w.ID == DungeonGeneratorEntranceWarpID);

            entrance.TargetBoard      = entranceBoard.BoardNum;        //should be this one.
            entrance.TargetWarpID     = originalExit.ID;
            originalExit.TargetBoard  = nox.CurrentBoard.BoardNum;
            originalExit.TargetWarpID = entrance.ID;

            nox.CurrentBoard.EntitiesToRemove.Add(nox.Player);
            nox.CurrentBoard       = entranceBoard;
            nox.Player.ParentBoard = entranceBoard;
            entranceBoard.Entities.Add(nox.Player);
            nox.Player.XPosition = originalExit.XPosition;
            nox.Player.YPosition = originalExit.YPosition;
            entranceBoard.UpdateLightmap(nox.Player, true);
            entranceBoard.Redraw();
            entranceBoard.PlayMusic();
            NoxicoGame.Immediate = true;
            NoxicoGame.Mode      = UserMode.Walkabout;
            NoxicoGame.Me.SaveGame();

            return(entranceBoard);
        }
コード例 #12
0
ファイル: Color.cs プロジェクト: dragontamer8740/Noxico
 static Color()
 {
     colorTable = Mix.GetTokenTree("knowncolors.tml", true);
 }
コード例 #13
0
ファイル: SoundSystem.cs プロジェクト: dragontamer8740/Noxico
        public void PlaySound(string name)
        {
            if (!Enabled || musicVolume == 0)
            {
                return;
            }

            if (name.StartsWith("set://"))
            {
                name = name.Substring(6);
                var setNode = soundLibrary.FirstOrDefault(x => x.Name == name);
                if (setNode == null)
                {
                    name = "-";
                }
                else
                {
                    name = "-";
                    var unmarked = new List <Token>();
                    foreach (var t in setNode.Tokens)
                    {
                        if (!t.HasToken("used"))
                        {
                            unmarked.Add(t);
                        }
                    }
                    if (unmarked.Count == 0)
                    {
                        foreach (var t in setNode.Tokens)
                        {
                            t.RemoveToken("used");
                            unmarked.Add(t);
                        }
                    }
                    while (unmarked.Count > 0)
                    {
                        var pick = Random.Next(unmarked.Count);
                        var file = unmarked[pick].Name;
                        if (!Mix.FileExists(file))
                        {
                            unmarked.RemoveAt(pick);
                        }
                        else
                        {
                            name = file;
                            unmarked[pick].AddToken("used");
                            break;
                        }
                    }
                }
            }

            if (sounds.ContainsKey(name) && sounds[name] == null)
            {
                return;
            }
            if (!sounds.ContainsKey(name))
            {
                if (Mix.FileExists(name))
                {
                    sounds.Add(name, new Sound(name, system));
                }
                else
                {
                    sounds.Add(name, null);
                    return;
                }
            }
            sounds[name].Play();
            sounds[name].Channel.SetVolume(soundVolume);
        }
コード例 #14
0
ファイル: SoundSystem.cs プロジェクト: dragontamer8740/Noxico
        public void PlayMusic(string name, bool fade = true)
        {
            if (!Enabled || musicVolume == 0)
            {
                return;
            }

            var set = targetSet;

            if (name.StartsWith("set://"))
            {
                set = name.Substring(6);
                var setNode = musicLibrary.FirstOrDefault(x => x.Name == set);
                if (setNode == null)
                {
                    name = "-";
                }
                else
                {
                    name = "-";
                    var unmarked = new List <Token>();
                    foreach (var t in setNode.Tokens)
                    {
                        if (!t.HasToken("used"))
                        {
                            unmarked.Add(t);
                        }
                    }
                    if (unmarked.Count == 0)
                    {
                        foreach (var t in setNode.Tokens)
                        {
                            t.RemoveToken("used");
                            unmarked.Add(t);
                        }
                    }
                    while (unmarked.Count > 0)
                    {
                        var pick = Random.Next(unmarked.Count);
                        var file = unmarked[pick].Name;
                        if (!Mix.FileExists(file))
                        {
                            unmarked.RemoveAt(pick);
                        }
                        else
                        {
                            name = file;
                            unmarked[pick].AddToken("used");
                            break;
                        }
                    }
                }
            }

            if (set == currentSet)
            {
                return;
            }

            if (fade && string.IsNullOrEmpty(FadeTarget) && musicChannel != null && name != musicPlaying)
            {
                FadeTarget  = name;
                targetSet   = set;
                fadeProcess = 300;
                return;
            }
            FadeTarget = null;
            if (name == "-")
            {
                if (musicChannel != null)
                {
                    musicChannel.Stop();
                }
                if (music != null)
                {
                    music.Release();
                }
                currentSet   = string.Empty;
                musicPlaying = string.Empty;
            }
            else if (musicPlaying != name)
            {
                if (Mix.FileExists(name))
                {
                    if (musicChannel != null)
                    {
                        musicChannel.Stop();
                    }
                    if (music != null)
                    {
                        music.Release();
                    }
                    var data  = Mix.GetBytes(name);
                    var fCSex = new FMOD.CreateSoundExInfo()
                    {
                        Size   = 216,
                        Length = (uint)data.Length
                    };
                    CheckError(system.CreateSound(data, FMOD.SoundMode.LoopNormal | FMOD.SoundMode.OpenMemory, ref fCSex, ref music));
                    system.PlaySound(music, false, ref musicChannel);
                    musicPlaying = name;
                    currentSet   = set;
                    musicChannel.SetVolume(musicVolume);
                    //NoxicoGame.HostForm.Text = file;
                }
                else
                {
                    Program.WriteLine("PlayMusic: couldn't load song \"{0}\".", name);
                }
            }
        }
コード例 #15
0
ファイル: Scenes.cs プロジェクト: dragontamer8740/Noxico
        public static void Engage(Character top, Character bottom, string name = "(start)")
        {
            if (sceneList == null)
            {
                sceneList = Mix.GetTokenTree("dialogue.tml", true);
            }

            SceneSystem.top    = top;
            SceneSystem.bottom = bottom;
            SceneSystem.actors = new[] { top, bottom };
            var dreaming = top.HasToken("dream");

            if (name.Contains('\xE064'))
            {
                name = name.Remove(name.LastIndexOf('\xE064'));
            }

            var openings = sceneList.Where(x => x.Name == "scene" && x.GetToken("name").Text == name).ToList();

            if (openings.Count == 0)
            {
                MessageBox.Notice(string.Format("Could not find a proper opening for scene name \"{0}\". Aborting.", name), true, "Uh-oh.");
                return;
            }
            var firstScene = openings.FirstOrDefault(i => SexManager.LimitsOkay(actors, i));
            var scenes     = new List <Token>()
            {
                firstScene
            };

            if (firstScene.HasToken("random"))
            {
                var randomKey = firstScene.GetToken("random").Text;
                foreach (var s in openings.Where(i => i != firstScene && i.HasToken("random") && i.GetToken("random").Text == randomKey && SexManager.LimitsOkay(actors, i)))
                {
                    scenes.Add(s);
                }
            }
            var scene = scenes.PickOne();

            var message = i18n.Viewpoint(ExtractParagraphsAndScripts(scene), SceneSystem.top, SceneSystem.bottom);
            var actions = ExtractActions(scene);

            if (actions.Count == 1)
            {
                var target = actions.First().Key;
                actions.Clear();
                actions.Add(target, "==>");
            }

            if (bottom == NoxicoGame.Me.Player.Character && !letBottomChoose)
            {
                if (actions.Count == 0)
                {
                    MessageBox.Notice(message, true, bottom.Name.ToString(true));
                }
                else
                {
                    var randomAction = actions.Keys.ToArray().PickOne();
                    actions.Clear();
                    actions.Add(randomAction, "==>");
                    MessageBox.List(message, actions, () => { Engage(SceneSystem.top, SceneSystem.bottom, (string)MessageBox.Answer); }, false, true, bottom.GetKnownName(true, true));
                }
            }
            else
            {
                letBottomChoose = false;
                if (actions.Count == 0)
                {
                    MessageBox.Notice(message, !dreaming, bottom.GetKnownName(true, true));
                }
                else
                {
                    MessageBox.List(message, actions, () => { Engage(SceneSystem.top, SceneSystem.bottom, (string)MessageBox.Answer); }, false, !dreaming, bottom.GetKnownName(true, true));
                }
            }

            if (dreaming)
            {
                new UIPNGBackground(Mix.GetBitmap("dream.png")).Draw();
            }
            else
            {
                NoxicoGame.Me.CurrentBoard.Redraw();
                NoxicoGame.Me.CurrentBoard.Draw();
            }
        }
コード例 #16
0
ファイル: Toolkit.cs プロジェクト: dragontamer8740/Noxico
        public static string Wordwrap(this string text, int length = 80)
        {
            var words = new List <Word>();
            var lines = new List <string>();

            text = text.Normalize();

            #region Hyphenator
            if (hyphenationRules == null)
            {
                var rulesRoot = Mix.GetTokenTree("i18n.tml").First(t => t.Name == "hyphenation");
                hyphenationRules = new List <Tuple <Regex, int> >();
                foreach (var rule in rulesRoot.Tokens)
                {
                    var newTuple = Tuple.Create(new Regex(rule.GetToken("pattern").Text), (int)rule.GetToken("cutoff").Value);
                    hyphenationRules.Add(newTuple);
                }
            }

            var newText = new StringBuilder();
            foreach (var inWord in text.Split(' '))
            {
                if (inWord.Contains('\u00AD') || inWord.Length < 6)
                {
                    newText.Append(inWord);
                    newText.Append(' ');
                    continue;
                }
                var word = inWord;
                foreach (var rule in hyphenationRules)
                {
                    if (rule.Item2 == -1 && rule.Item1.IsMatch(word))
                    {
                        break;
                    }
                    while (rule.Item1.IsMatch(word))
                    {
                        var match = rule.Item1.Match(word);
                        word = word.Substring(0, match.Index + rule.Item2) + '\u00AD' + word.Substring(match.Index + rule.Item2);
                    }
                }
                newText.Append(word);
                newText.Append(' ');
            }
            text = newText.ToString();
            text = text.Replace("\u00AD\u00AD", "\u00AD");
            text = Regex.Replace(text, "<(?:[\\w^­]+)(\u00AD)(?:[\\w^­]+)>", (m => m.Captures[0].Value.Replace("\u00AD", string.Empty)));
            #endregion

            var currentWord = new StringBuilder();
            var breakIt     = false;
            var spaceAfter  = false;
            var mandatory   = false;
            var softHyphen  = false;
            var color       = Color.Transparent;
            for (var i = 0; i < text.Length; i++)
            {
                var ch     = text[i];
                var nextCh = (i < text.Length - 1) ? text[i + 1] : '\0';
                if (ch == '<' && nextCh == 'c')
                {
                    if (text[i + 2] == '>')
                    {
                        color = Color.Transparent;
                        i    += 2;
                        continue;
                    }
                    var colorToken = new StringBuilder();
                    for (var j = i + 2; j < text.Length; j++)
                    {
                        if (text[j] == '>')
                        {
                            color = Color.FromName(colorToken.ToString());
                            i     = j;
                            break;
                        }
                        colorToken.Append(text[j]);
                    }
                    continue;
                }

                if ((ch == '\r' && nextCh != '\n') || ch == '\n')
                {
                    breakIt   = true;
                    mandatory = true;
                }
                else if (char.IsWhiteSpace(ch) && ch != '\u00A0')
                {
                    breakIt    = true;
                    spaceAfter = true;
                }
                else if (ch == '\u00AD')
                {
                    breakIt    = true;
                    softHyphen = true;
                }
                else if (char.IsPunctuation(ch) && !(ch == '(' || ch == ')' || ch == '\''))
                {
                    currentWord.Append(ch);
                    breakIt = true;
                }
                else
                {
                    currentWord.Append(ch);
                }


                if (breakIt)
                {
                    var newWord = new Word()
                    {
                        Content        = currentWord.ToString().Trim(),
                        SpaceAfter     = spaceAfter,
                        MandatoryBreak = mandatory,
                        SoftHyphen     = softHyphen,
                        Color          = color,
                    };
                    breakIt    = false;
                    spaceAfter = false;
                    mandatory  = false;
                    softHyphen = false;
                    words.Add(newWord);
                    currentWord.Clear();
                }
            }
            if (currentWord.ToString() != string.Empty)
            {
                var newWord = new Word()
                {
                    Content        = currentWord.ToString().Trim(),
                    SpaceAfter     = currentWord.ToString().EndsWith(' '),
                    MandatoryBreak = false,
                    SoftHyphen     = softHyphen,
                    Color          = color,
                };
                words.Add(newWord);
            }

            var line      = new StringBuilder();
            var spaceLeft = length;
            color = Color.Transparent;
            for (var i = 0; i < words.Count; i++)
            {
                var word = words[i];
                var next = (i < words.Count - 1) ? words[i + 1] : null;

                //Check for words longer than length? Should not happen with autohyphenator.

                //Reinsert color change without changing line length.
                if (word.Color != color)
                {
                    color = word.Color;
                    line.AppendFormat("<c{0}>", color == Color.Transparent ? string.Empty : color.Name);
                }

                if (word.Content == "\u2029")
                {
                    lines.Add(line.ToString().Trim());
                    lines.Add(string.Empty);
                    line.Clear();
                    spaceLeft = length;
                    continue;
                }

                if (word.SoftHyphen)
                {
                    if (next != null && spaceLeft - word.Length - next.Content.TrimEnd().Length <= 0)
                    {
                        word.Content   += '-';
                        word.SoftHyphen = false;
                    }
                }

                line.Append(word.Content);
                spaceLeft -= word.Length;
                if (next != null && spaceLeft - next.Content.TrimEnd().Length <= 0)
                {
                    if (!line.ToString().Trim().IsBlank())
                    {
                        lines.Add(line.ToString().Trim());
                    }
                    line.Clear();
                    spaceLeft = length;
                }
                else
                {
                    if (word.SpaceAfter)
                    {
                        line.Append(' ');
                        spaceLeft--;
                    }
                }

                if (word.MandatoryBreak)
                {
                    lines.Add(line.ToString().Trim());
                    line.Clear();
                    spaceLeft = length;
                    continue;
                }
            }
            if (!line.ToString().Trim().IsBlank())
            {
                lines.Add(line.ToString());
            }

            return(string.Join("\n", lines.ToArray()) + '\n');
        }
コード例 #17
0
        public static void ReadBook(string bookID)
        {
            var bookData = new string[0];

            try
            {
                bookData = Mix.GetString("books\\" + bookID + ".txt").Split('\n');
            }
            catch (FileNotFoundException)
            {
                bookData = i18n.GetString("book_404").Split('\n');
            }
            var text           = new StringBuilder();
            var header         = string.Empty;
            var identification = string.Empty;

            /*
             * var fonts = new Dictionary<string, int>()
             * {
             *      { "Hand", 0x200 },
             *      { "Carve", 0x234 },
             *      { "Daedric", 0x24E },
             *      { "Alternian", 0x268 },
             *      { "Felin", 0x282 },
             * };
             */
            for (var i = 0; i < bookData.Length; i++)
            {
                if (bookData[i].StartsWith("##"))
                {
                    header = bookData[i].Substring(3);
                    i++;
                    if (bookData[i].StartsWith("##"))
                    {
                        i++;                         //skip author
                    }
                    if (bookData[i].StartsWith("##"))
                    {
                        identification = bookData[i].Substring(3);
                        i++;
                    }

                    //var fontOffset = 0;
                    //var fontHasLower = false;
                    for (; i < bookData.Length; i++)
                    {
                        var line = bookData[i];
                        if (line.StartsWith("## "))
                        {
                            break;
                        }
                        for (int j = 0; j < line.Length; j++)
                        {
                            if (j < line.Length - 2 && line.Substring(j, 3) == "<b>")
                            {
                                text.Append("<cYellow>");
                                j += 2;
                            }
                            else if (j < line.Length - 3 && line.Substring(j, 4) == "</b>")
                            {
                                text.Append(" <c>");
                                j += 3;
                            }

                            /*
                             * else if (j < line.Length - 2 && line.Substring(j, 2) == "<f")
                             * {
                             *      var fontName = line.Substring(j + 2);
                             *      fontName = fontName.Remove(fontName.IndexOf('>'));
                             *      j = j + fontName.Length + 2;
                             *      fontOffset = fonts.ContainsKey(fontName) ? fonts[fontName] : 0;
                             *      fontHasLower = fontName == "Hand";
                             * }
                             * else
                             * {
                             *      if (fontOffset == 0) */
                            text.Append(line[j]);

                            /*
                             *      else
                             *      {
                             *              if (line[j] >= 'A' && line[j] <= 'Z')
                             *              {
                             *                      text.Append((char)((line[j] - 'A') + fontOffset));
                             *              }
                             *              else if (fontHasLower && line[j] >= 'a' && line[j] <= 'z')
                             *              {
                             *                      text.Append((char)((line[j] - 'a') + fontOffset + 0x1A));
                             *              }
                             *              else
                             *              {
                             *                      text.Append(line[j]);
                             *              }
                             *      }
                             * }
                             */
                        }
                        //text.Append(bookData[i]);
                        //text.AppendLine();
                    }
                    break;
                }
            }

            var player = NoxicoGame.Me.Player.Character;

            if (!identification.IsBlank())
            {
                foreach (var item in NoxicoGame.KnownItems.Where(ki => ki.HasToken("identify") && ki.GetToken("identify").Text == identification && !NoxicoGame.Identifications.Contains(ki.ID)))
                {
                    NoxicoGame.Identifications.Add(item.ID);
                }
                //text += "<cLime>(Your " + skillProper + " knowledge has gone up.)";
            }
            Plain(text.ToString(), header);
        }
コード例 #18
0
        public static string Viewpoint(this string message, Character top, Character bottom = null)
        {
#if DEBUG
            var player = NoxicoGame.Me.Player == null ? null : NoxicoGame.Me.Player.Character;
#else
            var player = NoxicoGame.Me.Player.Character;
#endif
            if (top == null)
            {
                top = player;
            }
            if (bottom == null)
            {
                bottom = top;
            }
            //var tIP = player == top;

            //Definitions used to be here. Now they're defined in i18n.lua.

            #region WordStructor filter
            var wordStructFilter = new Func <Token, Character, bool>((filter, who) =>
            {
                var env       = Lua.Environment;
                env.cultureID = who.Culture.ID;
                env.culture   = who.Culture;
                env.gender    = who.Gender;
                foreach (var stat in env.stats)
                {
                    var statName  = ((Neo.IronLua.LuaTable)stat.Value)["name"].ToString().ToLowerInvariant();
                    env[statName] = who.GetStat(statName);
                }

                env.pussyAmount  = who.HasToken("v****a") ? (who.GetToken("v****a").HasToken("dual") ? 2 : 1) : 0;
                env.penisAmount  = who.HasToken("penis") ? (who.GetToken("penis").HasToken("dual") ? 2 : 1) : 0;
                env.pussyWetness = who.HasToken("v****a") && who.GetToken("v****a").HasToken("wetness") ? who.GetToken("v****a").GetToken("wetness").Value : 0;
                env.cumAmount    = who.CumAmount;
                env.slime        = who.IsSlime;
                //return env.DoChunk("return " + filter.Text, "lol.lua").ToBoolean();
                return(Lua.Run("return " + filter.Text, env));
            });
            #endregion

            #region {} parser
            var regex = new Regex(@"{(?:{)? (?<first>\w*)   (?: \| (?<second>\w*) )? }(?:})?", RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
            message = regex.Replace(message, (match => top == player ? (match.Groups["second"].Success ? match.Groups["second"].Value : string.Empty) : match.Groups["first"].Value));
            #endregion
            #region [] parser
            regex = new Regex(@"
\[
	(?:(?<target>[tb\?]{1,2}):)?	#Optional target and :

	(?:								#One or more subcommands
		(?:\:?)						#Separating :, optional in case target already had one
		(?<subcom>[\w\/\-_\{\}]+)	#Command
	)*
\]", RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);

            var allMatches = regex.Matches(message);

            while (regex.IsMatch(message))
            {
                message = regex.Replace(message, (match =>
                {
                    var target = bottom;
                    var subcom = match.Groups["subcom"].Captures[0].Value;
                    var parms = new List <string>();

                    var targetGroup = match.Groups["target"].Value;

                    if (targetGroup.StartsWith('?'))
                    {
                        if (i18n.wordStructor == null)
                        {
                            i18n.wordStructor = Mix.GetTokenTree("wordstructor.tml", true);
                        }

                        if (targetGroup.Length == 2 && "tb".Contains(targetGroup[1]))
                        {
                            target = (targetGroup[1] == 't' ? top : bottom);
                        }

                        Lua.Environment.top = top;
                        Lua.Environment.bottom = bottom;
                        Lua.Environment.target = target;

                        var pToks = wordStructor.Where(x => x.Name == match.Groups["subcom"].Value).ToList();
                        if (pToks.Count == 0)
                        {
                            return(string.Format("<WordStructor fail: {0}>", match.Groups["subcom"].Value));
                        }
                        var pTok = pToks.PickWeighted();                         //pToks[Random.Next(pToks.Count)];
                        var pRes = pTok.Tokens.Where(x => !x.HasToken("filter") || wordStructFilter(x.GetToken("filter"), target)).ToList();
                        //Remove all less-specific options if any specific are found.
                        if (pRes.Any(x => x.HasToken("filter")))
                        {
                            pRes.RemoveAll(x => !x.HasToken("filter"));
                        }
                        return(pRes.PickOne().Text);
                    }
                    else if (targetGroup.StartsWith('t'))
                    {
                        target = top;
                    }

                    Lua.Environment.isPlayer = (target == player);
                    Lua.Environment.target = target;

                    //subcom = targetGroup;
                    //subcom = match.Groups["subcom"].Captures[0].Value;
                    for (var i = 1; i < match.Groups["subcom"].Captures.Count; i++)
                    {
                        var c = match.Groups["subcom"].Captures[i];
                        //Console.WriteLine(c);
                        parms.Add(c.Value.Replace('(', '[').Replace(')', ']'));
                    }

                    parms.Add(string.Empty);
                    parms.Add(string.Empty);
                    parms.Add(string.Empty);

                    //if (subcoms.ContainsKey(subcom)) return subcoms[subcom](target, parms);
                    if (SubCommands.ContainsKey(subcom))
                    {
                        return(SubCommands[subcom](target, parms).ToString());
                    }
                    return(string.Format("(?{0}?)", subcom));
                }));
            }
            message = Regex.Replace(message, @"\[\!(?<keybinding>.+?)\]", (match => Toolkit.TranslateKey(match.Groups["keybinding"].Value)));
            #endregion

            if (!message.Contains('"'))
            {
                return(message);
            }

            if (top == null)
            {
                return(message);
            }

            SpeechFilter speechFilter = top.SpeechFilter;
            if (speechFilter == null)
            {
                if (top.Culture.SpeechFilter != null)
                {
                    speechFilter = new SpeechFilter(x =>
                    {
                        Lua.RunFile(top.Culture.SpeechFilter);
                        x = Lua.Environment.SpeechFilter(x);
                        return(x);
                    });
                }
                if (impediments == null)
                {
                    impediments = Mix.GetTokenTree("impediments.tml");
                }
                foreach (var impediment in impediments)
                {
                    var apply = true;
                    foreach (var filter in impediment.Tokens.Where(t => t.Name == "have"))
                    {
                        var f = filter.Text.Split('=');
                        var p = top.Path(f[0]);
                        if (p == null || p.Text != f[1])
                        {
                            apply = false;
                            break;
                        }
                    }
                    if (apply)
                    {
                        var oldFilter = speechFilter;
                        speechFilter = new SpeechFilter(x =>
                        {
                            Lua.RunFile(impediment.GetToken("file").Text);
                            x = Lua.Environment.SpeechFilter(x);
                            return(oldFilter(x));
                        });
                    }
                }
                if (speechFilter == null)                    //Still?
                {
                    speechFilter = new SpeechFilter(x => x); //Then just assign a dummy so we don't do this all over and over again.
                }
                top.SpeechFilter = speechFilter;
            }
            message = message.SmartQuote(speechFilter);

            return(message);
        }
コード例 #19
0
ファイル: Options.cs プロジェクト: klorpa/Noxico
        public static void Handler()
        {
            if (Subscreens.FirstDraw)
            {
                Subscreens.FirstDraw = false;
                if (!FromTitle)
                {
                    UIManager.Initialize();
                    UIManager.Elements.Clear();
                }
                else
                {
                    //Leave the title screen background
                    UIManager.Highlight = UIManager.Elements[0];
                    UIManager.Elements.RemoveRange(3, UIManager.Elements.Count - 3);
                }

                window = new UIWindow(i18n.GetString("opt_title"))
                {
                    Left   = 0,
                    Top    = 0,
                    Width  = 80,
                    Height = 25,
                };
                window.Center();

                var speedLabel = new UILabel(i18n.GetString("opt_speed"));
                speedLabel.Move(3, 2, window);
                speed = new UITextBox(IniFile.GetValue("misc", "speed", "15"))
                {
                    Width   = 4,
                    Numeric = true
                };
                speed.Move(1, 1, speedLabel);

                var fonts            = Mix.GetFilesWithPattern("fonts\\*.png").Select(x => System.IO.Path.GetFileNameWithoutExtension(x)).ToArray();
                var currentFont      = IniFile.GetValue("misc", "font", "8x8-thin");
                var currentFontIndex = 0;
                if (fonts.Contains(currentFont))
                {
                    for (currentFontIndex = 0; currentFontIndex < fonts.Length; currentFontIndex++)
                    {
                        if (fonts[currentFontIndex] == currentFont)
                        {
                            break;
                        }
                    }
                }
                var fontLabel = new UILabel(i18n.GetString("opt_font"));
                fontLabel.Move(0, 3, speedLabel);
                font = new UIList(string.Empty, null, fonts, currentFontIndex)
                {
                    Width  = 20,
                    Height = 8,
                };
                font.Move(1, 1, fontLabel);
                font.Enter = (s, e) =>
                {
                    var previousFont = font.Text;
                    IniFile.SetValue("misc", "font", font.Text);
                    NoxicoGame.HostForm.RestartGraphics(false);
                    IniFile.SetValue("misc", "font", previousFont);
                };
                font.EnsureVisible();

                var screenColsLabel = new UILabel(i18n.GetString("opt_screencols"));
                screenColsLabel.MoveBelow(-1, 1, font);
                screenCols = new UITextBox(IniFile.GetValue("misc", "screencols", "80"))
                {
                    Width   = 4,
                    Numeric = true
                };
                screenCols.Move(1, 1, screenColsLabel);
                var screenRowsLabel = new UILabel(i18n.GetString("opt_screenrows"));
                screenRowsLabel.Move(-1, 1, screenCols);
                screenRows = new UITextBox(IniFile.GetValue("misc", "screenrows", "25"))
                {
                    Width   = 4,
                    Numeric = true
                };
                screenRows.Move(1, 1, screenRowsLabel);
                screenCols.Enter = screenRows.Enter = (s, e) =>
                {
                    var resetGraphics = false;
                    var i             = int.Parse(screenCols.Text);
                    if (i < 80)
                    {
                        i = 80;
                    }
                    if (i > 300)
                    {
                        i = 300;
                    }
                    if (i != Program.Cols)
                    {
                        resetGraphics = true;
                    }
                    Program.Cols = i;
                    IniFile.SetValue("misc", "screencols", i);
                    i = int.Parse(screenRows.Text);
                    if (i < 25)
                    {
                        i = 25;
                    }
                    if (i > 100)
                    {
                        i = 100;
                    }
                    if (i != Program.Rows)
                    {
                        resetGraphics = true;
                    }
                    Program.Rows = i;
                    IniFile.SetValue("misc", "screenrows", i);
                    if (resetGraphics)
                    {
                        NoxicoGame.HostForm.RestartGraphics(true);
                        window.Center();
                        UIManager.ReMove();
                    }
                    Subscreens.Redraw = true;
                    NoxicoGame.Me.CurrentBoard.AimCamera();
                    NoxicoGame.Me.CurrentBoard.Redraw();
                    NoxicoGame.Me.CurrentBoard.Draw();
                };

                var miscWindow = new UIWindow(i18n.GetString("opt_misc"))
                {
                    Width  = 50,
                    Height = 11,
                };
                miscWindow.MoveBeside(2, 0, speedLabel);

                rememberPause = new UIToggle(i18n.GetString("opt_rememberpause"))
                {
                    Checked    = IniFile.GetValue("misc", "rememberpause", true),
                    Background = Color.Transparent,
                };
                rememberPause.Move(2, 1, miscWindow);

                vistaSaves = new UIToggle(i18n.GetString("opt_vistasaves"))
                {
                    Checked    = IniFile.GetValue("misc", "vistasaves", true),
                    Enabled    = Vista.IsVista,
                    Background = Color.Transparent,
                };
                vistaSaves.MoveBelow(0, 1, rememberPause);

                xInput = new UIToggle(i18n.GetString("opt_xinput"))
                {
                    Checked    = IniFile.GetValue("misc", "xinput", true),
                    Enabled    = Vista.IsVista,
                    Background = Color.Transparent,
                };
                xInput.MoveBelow(0, 1, vistaSaves);

                imperial = new UIToggle(i18n.GetString("opt_imperial"))
                {
                    Checked    = IniFile.GetValue("misc", "imperial", false),
                    Background = Color.Transparent,
                };
                imperial.MoveBelow(0, 1, xInput);

                fourThirtySeven = new UIToggle(i18n.GetString("opt_437"))
                {
                    Checked    = IniFile.GetValue("misc", "437", false),
                    Background = Color.Transparent,
                };
                fourThirtySeven.MoveBelow(0, 1, imperial);

                var audioWindow = new UIWindow(i18n.GetString("opt_audio"))
                {
                    Width  = 30,
                    Height = 8,
                };
                audioWindow.MoveBelow(0, 1, miscWindow);

                enableAudio = new UIToggle(i18n.GetString("opt_enableaudio"))
                {
                    Checked    = IniFile.GetValue("audio", "enabled", true),
                    Background = Color.Transparent,
                };
                enableAudio.Move(2, 1, audioWindow);

                var musicVolumeLabel = new UILabel(i18n.GetString("opt_musicvolume"));
                musicVolumeLabel.MoveBelow(0, 1, enableAudio);
                musicVolume = new UITextBox(IniFile.GetValue("audio", "musicvolume", "100"));
                musicVolume.Move(1, 1, musicVolumeLabel);
                var soundVolumeLabel = new UILabel(i18n.GetString("opt_soundvolume"));
                soundVolumeLabel.Move(-1, 1, musicVolume);
                soundVolume = new UITextBox(IniFile.GetValue("audio", "soundvolume", "100"));
                soundVolume.Move(1, 1, soundVolumeLabel);

                saveButton = new UIButton(i18n.GetString("opt_save"), (s, e) =>
                {
                    var i = int.Parse(speed.Text);
                    if (i < 1)
                    {
                        i = 1;
                    }
                    if (i > 200)
                    {
                        i = 200;
                    }
                    IniFile.SetValue("misc", "speed", i);
                    IniFile.SetValue("misc", "font", font.Text);
                    IniFile.SetValue("misc", "rememberpause", rememberPause.Checked);
                    IniFile.SetValue("misc", "vistasaves", vistaSaves.Checked);
                    IniFile.SetValue("misc", "xinput", xInput.Checked);
                    IniFile.SetValue("misc", "imperial", imperial.Checked);
                    IniFile.SetValue("misc", "437", fourThirtySeven.Checked);
                    Vista.GamepadEnabled = xInput.Checked;

                    var resetGraphics = false;
                    i = int.Parse(screenCols.Text);
                    if (i < 80)
                    {
                        i = 80;
                    }
                    if (i > 300)
                    {
                        i = 300;
                    }
                    if (i != Program.Cols)
                    {
                        resetGraphics = true;
                    }
                    Program.Cols = i;
                    IniFile.SetValue("misc", "screencols", i);
                    i = int.Parse(screenRows.Text);
                    if (i < 25)
                    {
                        i = 25;
                    }
                    if (i > 100)
                    {
                        i = 100;
                    }
                    if (i != Program.Rows)
                    {
                        resetGraphics = true;
                    }
                    Program.Rows = i;
                    IniFile.SetValue("misc", "screenrows", i);

                    IniFile.SetValue("misc", "imperial", imperial.Checked);
                    IniFile.SetValue("audio", "enabled", enableAudio.Checked);
                    i = int.Parse(musicVolume.Text);
                    if (i < 0)
                    {
                        i = 0;
                    }
                    if (i > 100)
                    {
                        i = 100;
                    }
                    NoxicoGame.Sound.MusicVolume = i / 100f;
                    IniFile.SetValue("audio", "musicvolume", i);
                    i = int.Parse(soundVolume.Text);
                    if (i < 0)
                    {
                        i = 0;
                    }
                    if (i > 100)
                    {
                        i = 100;
                    }
                    NoxicoGame.Sound.SoundVolume = i / 100f;
                    IniFile.SetValue("audio", "soundvolume", i);

                    if (!enableAudio.Checked && NoxicoGame.Sound != null)
                    {
                        NoxicoGame.Sound.ShutDown();
                    }
                    else if (enableAudio.Checked && !NoxicoGame.Sound.Enabled)
                    {
                        NoxicoGame.Sound = new SoundSystem();
                        if (NoxicoGame.Me.CurrentBoard != null)
                        {
                            NoxicoGame.Me.CurrentBoard.PlayMusic();
                        }
                    }

                    if (resetGraphics)
                    {
                        NoxicoGame.HostForm.RestartGraphics(true);
                    }

                    IniFile.Save(string.Empty);
                    cancelButton.DoEnter();
                })
                {
                    Width = 16
                };
                saveButton.MoveBeside(2, 0, audioWindow);
                keysButton = new UIButton(i18n.GetString("opt_keys"), (s, e) =>
                {
                    Controls.Open();
                })
                {
                    Width = 16
                };
                keysButton.MoveBelow(0, 1, saveButton);
                openButton = new UIButton(i18n.GetString("opt_open"), (s, e) =>
                {
                    System.Diagnostics.Process.Start(NoxicoGame.HostForm.IniPath);
                })
                {
                    Width = 16
                };
                openButton.MoveBelow(0, 1, keysButton);
                cancelButton = new UIButton(i18n.GetString("opt_cancel"), (s, e) =>
                {
                    UIManager.Elements.Clear();
                    NoxicoGame.ClearKeys();
                    NoxicoGame.Immediate = true;
                    NoxicoGame.Me.CurrentBoard.Redraw();
                    NoxicoGame.Me.CurrentBoard.Draw(true);
                    NoxicoGame.Mode = UserMode.Walkabout;
                    if (FromTitle)
                    {
                        Introduction.Title();
                    }
                    Subscreens.FirstDraw = true;
                })
                {
                    Width = 16
                };
                cancelButton.MoveBelow(0, 1, openButton);

                UIManager.Elements.Add(window);
                UIManager.Elements.Add(speedLabel);
                UIManager.Elements.Add(speed);
                UIManager.Elements.Add(fontLabel);
                UIManager.Elements.Add(font);
                UIManager.Elements.Add(screenColsLabel);
                UIManager.Elements.Add(screenCols);
                UIManager.Elements.Add(screenRowsLabel);
                UIManager.Elements.Add(screenRows);
                UIManager.Elements.Add(miscWindow);
                UIManager.Elements.Add(rememberPause);
                UIManager.Elements.Add(vistaSaves);
                UIManager.Elements.Add(xInput);
                UIManager.Elements.Add(imperial);
                UIManager.Elements.Add(fourThirtySeven);
                UIManager.Elements.Add(audioWindow);
                UIManager.Elements.Add(enableAudio);
                UIManager.Elements.Add(musicVolumeLabel);
                UIManager.Elements.Add(musicVolume);
                UIManager.Elements.Add(soundVolumeLabel);
                UIManager.Elements.Add(soundVolume);
                UIManager.Elements.Add(saveButton);
                UIManager.Elements.Add(keysButton);
                UIManager.Elements.Add(openButton);
                UIManager.Elements.Add(cancelButton);

                Subscreens.FirstDraw = false;
                Subscreens.Redraw    = true;
            }
            if (Subscreens.Redraw)
            {
                Subscreens.Redraw = false;
                UIManager.Draw();
            }

            if (NoxicoGame.IsKeyDown(KeyBinding.Back) || Vista.Triggers == XInputButtons.B)
            {
                cancelButton.DoEnter();
            }
            else
            {
                UIManager.CheckKeys();
            }
        }
コード例 #20
0
        private static void Initialize()
        {
            if (words != null)
            {
                return;
            }
            words = new Dictionary <string, string>();
            var x = Mix.GetTokenTree("i18n.tml");

            foreach (var word in x.Find(t => t.Name == "words").Tokens)
            {
                if (word.Text == null && word.HasToken("#text"))
                {
                    words[word.Name] = word.GetToken("#text").Text;
                }
                else
                {
                    words[word.Name] = word.Text;
                }
            }

#if DEBUG
            var sanityCheck = new[] {
                "A|pie|a",
                "A|apple|an",
                "P|hoof|hooves",
                "S|hooves|hoof",
                "P|cheap piece of shit|cheap pieces of shit",
                "S|cheap pieces of shit|cheap piece of shit",
                "P|vortex|vortices",
                "S|cortices|cortex",
                "P|pegasus|pegasori",
                "S|pegasori|pegasus",
                "P|alga|algæ",
                "S|kunai|kunai",
                "P|kunai of the dawn|kunai of the dawn",
                "p|Kawa|Kawa's",
                "p|it|its",
                "p|Sassafrass|Sassafrass'",
            };
            foreach (var test in sanityCheck.Select(t => t.Split('|')))
            {
                var checkFrom = test[1];
                var checkTo   = test[2];
                var result    = string.Empty;
                if (test[0] == "P")
                {
                    result = Pluralize(checkFrom, 2);
                }
                else if (test[0] == "S")
                {
                    result = Singularize(checkFrom);
                }
                else if (test[0] == "A")
                {
                    result = GetArticle(checkFrom);
                }
                else if (test[0] == "p")
                {
                    result = Possessive(checkFrom);
                }
                if (result != checkTo)
                {
                    throw new Exception(string.Format("Sanity check on pluralizer failed. Expected \"{0}\" but got \"{1}\".", checkTo, result));
                }
            }
#endif
        }
コード例 #21
0
        public void RestartGraphics(bool full)
        {
            pngFont = IniFile.GetValue("misc", "font", "8x16-bold");
            if (!Mix.FileExists("fonts\\" + pngFont + ".png"))
            {
                pngFont = "8x16-bold";
                if (!Mix.FileExists("fonts\\" + pngFont + ".png"))
                {
                    SystemMessageBox.Show(this, "Could not find font bitmaps. Please redownload the game.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Close();
                    return;
                }
            }
            var fontBitmap = Mix.GetBitmap("fonts\\" + pngFont + ".png");

            cellWidth  = fontBitmap.Width / 32;
            cellHeight = fontBitmap.Height / 32;

            IsSquare = cellWidth == cellHeight;

            Program.Cols = IniFile.GetValue("misc", "screencols", Program.Cols);
            Program.Rows = IniFile.GetValue("misc", "screenrows", Program.Rows);
            if (full)
            {
                image         = new Cell[Program.Cols, Program.Rows];
                previousImage = new Cell[Program.Cols, Program.Rows];
            }

            CachePNGFont(fontBitmap);

            fourThirtySeven = IniFile.GetValue("misc", "437", false);
            youtube         = IniFile.GetValue("misc", "youtube", false);
            ClientSize      = new Size(Program.Cols * cellWidth, Program.Rows * cellHeight);
            if (youtube)
            {
                //Find nearest YT size
                var eW = Program.Cols * cellWidth;
                var eH = Program.Rows * cellHeight;
                if (eW <= 854 || eH <= 480)
                {
                    ClientSize = new Size(854, 480);
                }
                else if (eW <= 1280 || eH <= 720)
                {
                    ClientSize = new Size(1280, 720);
                }
                else
                {
                    ClientSize = new Size(1920, 1080);
                }

                var prime = Screen.FromRectangle(ClientRectangle).Bounds;
                if (ClientSize.Width == prime.Width && ClientSize.Height == prime.Height)
                {
                    FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                    Left            = Top = 0;
                }
                else
                {
                    FormBorderStyle = IniFile.GetValue("misc", "border", true) ? System.Windows.Forms.FormBorderStyle.FixedSingle : System.Windows.Forms.FormBorderStyle.None;
                }
                youtubeRect = new System.Drawing.Rectangle((ClientSize.Width / 2) - (eW / 2), (ClientSize.Height / 2) - (eH / 2), eW, eH);
            }
            else
            {
                FormBorderStyle = IniFile.GetValue("misc", "border", true) ? System.Windows.Forms.FormBorderStyle.FixedSingle : System.Windows.Forms.FormBorderStyle.None;
            }

            Show();
            Refresh();

            backBuffer   = new Bitmap(Program.Cols * cellWidth, Program.Rows * cellHeight, PixelFormat.Format24bppRgb);
            scrollBuffer = new Bitmap(Program.Cols * cellWidth, Program.Rows * cellHeight, PixelFormat.Format24bppRgb);
            for (int row = 0; row < Program.Rows; row++)
            {
                for (int col = 0; col < Program.Cols; col++)
                {
                    previousImage[col, row].Character = '\uFFFE';
                }
            }
        }
コード例 #22
0
ファイル: BoardDrawing.cs プロジェクト: klorpa/Noxico
        public void MergeBitmap(string fileName, string tiledefs)
        {
            var bitmap  = Mix.GetBitmap(fileName);
            var tileset = new Token();

            tileset.AddSet(Mix.GetTokenTree(tiledefs, true));
            var width  = Width;
            var height = Height;

            if (width > bitmap.Width)
            {
                width = bitmap.Width;
            }
            if (height > bitmap.Height)
            {
                height = bitmap.Height;
            }
            for (var y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    var color = bitmap.GetPixel(x, y);
                    if (color.Name == "ff000000" || color.A == 0)
                    {
                        continue;
                    }
                    var key = color.Name.Substring(2).ToUpperInvariant();
                    if (!tileset.HasToken(key))
                    {
                        continue;
                    }
                    var tile = tileset.GetToken(key);

                    //Keep the original tile, but drain it.
                    if (tile.Text == "drain")
                    {
                        this.Tilemap[x, y].Fluid = Fluids.Dry;
                        continue;
                    }

                    this.Tilemap[x, y].Index = TileDefinition.Find(tile.Text).Index;

                    if (tile.Text.StartsWith("doorway"))
                    {
                        var door = new Door()
                        {
                            XPosition       = x,
                            YPosition       = y,
                            ForegroundColor = this.Tilemap[x, y].Definition.Background,
                            BackgroundColor = this.Tilemap[x, y].Definition.Background.Darken(),
                            ID          = "mergeBitmap_Door" + x + "_" + y,
                            ParentBoard = this,
                            Closed      = tile.Text.EndsWith("Closed"),
                            Glyph       = '+'
                        };
                        this.Entities.Add(door);
                    }

                    if (tile.HasToken("clutter"))
                    {
                        var nc = new Clutter()
                        {
                            XPosition   = x,
                            YPosition   = y,
                            ParentBoard = this
                        };
                        this.Entities.Add(nc);
                        var properties = tile.GetToken("clutter");
                        foreach (var property in properties.Tokens)
                        {
                            switch (property.Name)
                            {
                            case "id": nc.ID = property.Text; break;

                            case "name": nc.Name = property.Text; break;

                            case "desc": nc.Description = property.Text; break;

                            case "glyph": nc.Glyph = (int)property.Value; break;

                            case "fg":
                                if (property.Text.StartsWith('#'))
                                {
                                    nc.ForegroundColor = Color.FromCSS(property.Text);
                                }
                                else
                                {
                                    nc.ForegroundColor = Color.FromName(property.Text);
                                }
                                break;

                            case "bg":
                                if (property.Text.StartsWith('#'))
                                {
                                    nc.BackgroundColor = Color.FromCSS(property.Text);
                                }
                                else
                                {
                                    nc.BackgroundColor = Color.FromName(property.Text);
                                }
                                break;

                            case "block": nc.Blocking = true; break;

                            case "burns": nc.CanBurn = true; break;
                            }
                        }
                    }

                    if (tile.HasToken("unique"))
                    {
                        var unique  = tile.GetToken("unique");
                        var newChar = new BoardChar(Character.GetUnique(unique.Text))
                        {
                            XPosition   = x,
                            YPosition   = y,
                            ParentBoard = this
                        };
                        this.Entities.Add(newChar);
                        newChar.AssignScripts(unique.Text);
                        newChar.ReassignScripts();
                    }

                    if (!tile.HasToken("fluid"))
                    {
                        this.Tilemap[x, y].Fluid = Fluids.Dry;
                    }
                    else
                    {
                        this.Tilemap[x, y].Fluid = (Fluids)Enum.Parse(typeof(Fluids), tile.GetToken("fluid").Text, true);
                    }
                }
            }
            this.ResolveVariableWalls();
        }
コード例 #23
0
        public void Create(BiomeData biome, string templateSet)
        {
            Culture = Culture.Cultures[biome.Cultures.PickOne()];
            DungeonGenerator.DungeonGeneratorBiome = BiomeData.Biomes.IndexOf(biome);
            this.biome = biome;
            map        = new int[Board.Width, Board.Height];

            plotCols = Board.Width / plotWidth;
            plotRows = Board.Height / plotHeight;
            if (plotCols * plotWidth < Board.Width)
            {
                plotWidth = Board.Width / plotCols;
            }
            if (plotRows * plotHeight < Board.Height)
            {
                plotHeight = Board.Height / plotRows;
            }

            plots = new Building[plotCols, plotRows];

            if (templates == null)
            {
                templates = new Dictionary <string, List <Template> >();
                var templateSource = Mix.GetTokenTree("buildings.tml");
                CreateRotationsAndFlips(templateSource);
                foreach (var set in templateSource.Where(x => x.Name == "set"))
                {
                    var thisSet = new List <Template>();
                    foreach (var template in set.Tokens.Where(x => x.Name == "template"))
                    {
                        thisSet.Add(new Template(template));
                    }
                    templates.Add(set.Text, thisSet);
                }
            }

            var spill = new Building("<spillover>", null, 0, 0, Culture.DefaultCulture);

            //var justPlaced = false;

            for (var row = 0; row < plotRows; row++)
            {
                for (var col = 0; col < plotCols; col++)
                {
                    if (plots[col, row].BaseID == "<spillover>")
                    {
                        continue;
                    }
                    //Small chance of not having anything here, for variation.
                    if (Random.NextDouble() < 0.2)
                    {
                        //justPlaced = false;
                        continue;
                    }
                    var newTemplate = templates[templateSet].PickOne();
                    //TODO: check if chosen template spills over and if so, if there's room. For now, assume all templates are <= 8
                    //Each plot is 8x8. Given that and the template size, we can wiggle them around a bit from 0 to (8 - tSize).
                    var sX = newTemplate.Width < plotWidth?Random.Next(1, plotWidth - newTemplate.Width) : 0;

                    var sY = newTemplate.Height < plotHeight?Random.Next(1, plotHeight - newTemplate.Height) : 0;

                    //NEW: check for water in this plot.
                    var water = 0;
                    for (var y = 0; y < newTemplate.Height; y++)
                    {
                        for (var x = 0; x < newTemplate.Width; x++)
                        {
                            if (Board.Tilemap[(col * plotWidth) + x, (row * plotHeight) + y].Fluid != Fluids.Dry)
                            {
                                water++;
                            }
                        }
                    }
                    if (water > 0)
                    {
                        continue;
                    }

                    //Later on, we might be able to wiggle them out of their assigned plot a bit.
                    var newBuilding = new Building(string.Format("house{0}x{1}", row, col), newTemplate, sX, sY, Culture);
                    plots[col, row] = newBuilding;
                    //justPlaced = true;
                }
            }
        }
コード例 #24
0
ファイル: BoardDrawing.cs プロジェクト: klorpa/Noxico
        public void GenerateTown(bool rename, bool vendors, List <string> vendorTypes)
        {
            this.BoardType = BoardType.Town;
            this.GetToken("encounters").Value = 0;
            this.GetToken("encounters").Tokens.Clear();
            var townGen = new TownGenerator();

            townGen.Board = this;
            var biome       = BiomeData.Biomes[(int)this.GetToken("biome").Value];
            var cultureName = biome.Cultures.PickOne();

            townGen.Culture = Culture.Cultures[cultureName];
            townGen.Create(biome);
            townGen.ToTilemap(ref this.Tilemap);
            townGen.ToSectorMap(this.Sectors);
            this.Music = biome.Realm == Realms.Nox ? "set://Town" : "set://Dungeon";
            this.AddToken("culture", 0, cultureName);

            if (rename)
            {
                while (true)
                {
                    var newName = Culture.GetName(townGen.Culture.TownName, Culture.NameType.Town);
                    if (NoxicoGame.Me.Boards.Find(b => b != null && b.Name == newName) == null)
                    {
                        this.Name = newName;
                        break;
                    }
                }
                //this.ID = string.Format("{0}x{1}-{2}", this.cx, y, this.Name.ToID());
            }

            if (vendors)
            {
                if (vendorTypes == null)
                {
                    vendorTypes = new List <string>();
                    var lootData = Mix.GetTokenTree("loot.tml", true);
                    foreach (var filter in lootData.Where(t => t.Path("filter/vendorclass") != null).Select(t => t.Path("filter/vendorclass")))
                    {
                        if (!vendorTypes.Contains(filter.Text))
                        {
                            vendorTypes.Add(filter.Text);
                        }
                    }
                }

                var citizens = this.Entities.OfType <BoardChar>().Where(e => e.Character.Path("role/vendor") == null).ToList();
                foreach (var vendorType in vendorTypes)
                {
                    if (Random.Flip())
                    {
                        continue;
                    }
                    if (citizens.Count == 0)                     //Shouldn't happen, but who knows.
                    {
                        break;
                    }
                    var chosenCitizen = citizens.PickOne();
                    citizens.Remove(chosenCitizen);
                    var spouse = chosenCitizen.Character.Spouse;
                    if (spouse != null)
                    {
                        citizens.Remove(spouse.BoardChar);
                    }
                    var newVendor   = chosenCitizen.Character;
                    var vendorStock = newVendor.GetToken("items");
                    newVendor.RemoveAll("role");
                    newVendor.AddToken("role").AddToken("vendor").AddToken("class", 0, vendorType);
                    newVendor.GetToken("money").Value = 1000 + (Random.Next(0, 20) * 50);
                    Program.WriteLine("*** {0} of {2} is now a {1} ***", newVendor.Name.ToString(true), vendorType, this.Name);
                    chosenCitizen.RestockVendor();
                }
            }
        }
コード例 #25
0
ファイル: Introduction.cs プロジェクト: klorpa/Noxico
        /// <summary>
        /// Goes through bodyplans.tml to get a list of PlayableRaces.
        /// </summary>
        private static void CollectPlayables()
        {
            playables = new List <PlayableRace>();
            Program.WriteLine("Collecting playables...");
            foreach (var bodyPlan in Character.Bodyplans.Where(t => t.Name == "bodyplan"))
            {
                var id   = bodyPlan.Text;
                var plan = bodyPlan.Tokens;
                if (!bodyPlan.HasToken("playable"))
                {
                    continue;
                }
                Program.WriteLine(" * Parsing {0}...", id);

                var sexlocks = new[] { true, true, true, false };
                if (bodyPlan.HasToken("normalgenders"))
                {
                    sexlocks = new[] { true, true, false, false }
                }
                ;
                else if (bodyPlan.HasToken("maleonly"))
                {
                    sexlocks = new[] { true, false, false, false }
                }
                ;
                else if (bodyPlan.HasToken("femaleonly"))
                {
                    sexlocks = new[] { false, true, false, false }
                }
                ;
                else if (bodyPlan.HasToken("hermonly"))
                {
                    sexlocks = new[] { false, false, true, false }
                }
                ;
                else if (bodyPlan.HasToken("neuteronly"))
                {
                    sexlocks = new[] { false, false, false, true }
                }
                ;
                if (bodyPlan.HasToken("allowneuter"))
                {
                    sexlocks[3] = true;
                }

                //Use the ID ("bodyplan: example") as the name, unless there's a "playable: proper name".
                var name = id.Replace('_', ' ').Titlecase();
                if (!bodyPlan.GetToken("playable").Text.IsBlank())
                {
                    name = bodyPlan.GetToken("playable").Text;
                }

                var bestiary = bodyPlan.HasToken("bestiary") ? bodyPlan.GetToken("bestiary").Text : string.Empty;

                //Figure out what to put on page two.
                //By default, we assume skin and hair colors can be edited.
                //Most bodyplans will be different, though.
                var colorItems = new Dictionary <string, UIElement>();
                var editables  = "skin/color|Skin color, hair/color|Hair color";                //path|Label, path|Label...
                if (bodyPlan.HasToken("editable"))
                {
                    editables = bodyPlan.GetToken("editable").Text;
                }

                var xScale   = Program.Cols / 80f;
                var yScale   = Program.Rows / 25f;
                var ccpage   = Mix.GetBitmap("ccpage.png");
                var pageLeft = Program.Cols - ccpage.Width - (int)(2 * yScale);
                var pageTop  = Program.Rows - (ccpage.Height / 2);

                var labelL = pageLeft + 5;
                var cntrlL = labelL + 2;
                var top    = (pageTop / 2) + 5;
                var width  = 26;

                foreach (var aspect in editables.Split(','))
                {
                    if (aspect.IsBlank())
                    {
                        continue;
                    }
                    var a     = aspect.Trim().Split('|');
                    var path  = a[0];
                    var label = a[1];
                    var t     = bodyPlan.Path(path).Text;
                    if (t.StartsWith("oneof"))
                    {
                        t = t.Substring(6);
                    }
                    var oneof = t.Split(',').ToList();
                    var items = new List <string>();
                    colorItems.Add("lbl-" + path, new UILabel(label)
                    {
                        Left = labelL, Top = top, Foreground = Color.Gray
                    });
                    foreach (var i in oneof)
                    {
                        var iT = i.Trim();
                        iT = iT.IsBlank(i18n.GetString("[none]", false), iT.Titlecase());
                        if (!items.Contains(iT))
                        {
                            items.Add(iT);
                        }
                    }
                    if (label.EndsWith("color", StringComparison.InvariantCultureIgnoreCase))
                    {
                        for (var i = 0; i < items.Count; i++)
                        {
                            items[i] = Color.NameColor(items[i]).Titlecase();
                        }
                        colorItems.Add(path, new UIColorList()
                        {
                            Items = items, Left = cntrlL, Top = top + 1, Width = width, Foreground = Color.Black, Background = Color.Transparent, Index = 0
                        });
                    }
                    else
                    {
                        colorItems.Add(path, new UISingleList()
                        {
                            Items = items, Left = cntrlL, Top = top + 1, Width = width, Foreground = Color.Black, Background = Color.Transparent, Index = 0
                        });
                    }
                    top += 2;
                }

                playables.Add(new PlayableRace()
                {
                    ID = id, Name = name, Bestiary = bestiary, ColorItems = colorItems, SexLocks = sexlocks
                });
            }
        }
コード例 #26
0
        /// <summary>
        /// Returns a list of possible Recipes that a given character is able to craft.
        /// </summary>
        /// <param name="carrier">Probably the player character.</param>
        /// <returns>A list of possible recipes. Keep it, and invoke Apply on the player's choice.</returns>
        public static List <Recipe> GetPossibilities(Character carrier)
        {
            Carrier         = carrier;
            ItemsToWorkWith = Carrier.GetToken("items");
            var results = new List <Recipe>();
            var tml     = Mix.GetTokenTree("crafting.tml");

            foreach (var recipe in tml)
            {
                var considered = new List <Token>();
                var resultName = "?";
                if (recipe.HasToken("produce"))
                {
                    resultName = recipe.GetToken("produce").Text;
                }
                var resultingSourceItem = default(InventoryItem);

                var steps     = recipe.Tokens;
                var stepRefs  = new Token[steps.Count()];
                var i         = 0;
                var newRecipe = new Recipe();
                foreach (var step in steps)
                {
                    if (step.Name == "consume" || step.Name == "require")
                    {
                        var amount = 1;
                        if (step.HasToken("amount"))
                        {
                            amount = (int)step.GetToken("amount").Value;
                        }

                        var numFound = 0;
                        if (step.Text == "<anything>")
                        {
                            foreach (var carriedItem in ItemsToWorkWith.Tokens)
                            {
                                var knownItem = NoxicoGame.KnownItems.Find(ki => ki.ID == carriedItem.Name);
                                if (knownItem == null)
                                {
                                    Program.WriteLine("Crafting: don't know what a {0} is.", carriedItem.Name);
                                    continue;
                                }

                                var withs    = step.GetAll("with");
                                var withouts = step.GetAll("withouts");
                                var okay     = 0;
                                foreach (var with in withs)
                                {
                                    if (knownItem.HasToken(with.Text))
                                    {
                                        okay++;
                                    }
                                }
                                foreach (var without in withouts)
                                {
                                    if (knownItem.HasToken(without.Text))
                                    {
                                        okay = 0;
                                    }
                                }
                                if (okay < withs.Count())
                                {
                                    continue;
                                }

                                if (carriedItem.HasToken("charge"))
                                {
                                    numFound += (int)carriedItem.GetToken("charge").Value;
                                }
                                else
                                {
                                    numFound++;
                                }
                                stepRefs[i] = carriedItem;

                                if (i == 0)
                                {
                                    resultingSourceItem = knownItem;
                                }
                            }
                        }
                        else if (step.Text == "book")
                        {
                            //TODO: see if a book with the given ID is marked as read.
                        }
                        else
                        {
                            foreach (var carriedItem in ItemsToWorkWith.Tokens.Where(t => t.Name == step.Text))
                            {
                                var knownItem = NoxicoGame.KnownItems.Find(ki => ki.ID == carriedItem.Name);
                                if (knownItem == null)
                                {
                                    Program.WriteLine("Crafting: don't know what a {0} is.", carriedItem.Name);
                                    continue;
                                }

                                if (carriedItem.HasToken("charge"))
                                {
                                    numFound += (int)carriedItem.GetToken("charge").Value;
                                }
                                else
                                {
                                    numFound++;
                                }
                                stepRefs[i] = carriedItem;

                                if (i == 0)
                                {
                                    resultingSourceItem = knownItem;
                                }
                            }
                        }

                        if (numFound < amount)
                        {
                            Program.WriteLine("Crafting: not enough {0} to craft {1}.", step.Text, resultName);
                            break;
                        }
                        if (step.Name == "consume")
                        {
                            newRecipe.Actions.Add(new CraftConsumeItemAction()
                            {
                                Target = stepRefs[i]
                            });
                        }
                    }
                    else if (step.Name == "produce")
                    {
                        var itemMade = new Token(step.Text);
                        itemMade.Tokens.AddRange(step.Tokens);
                        newRecipe.Actions.Add(new CraftProduceItemAction()
                        {
                            Target = itemMade
                        });
                        var resultingKnownItem = NoxicoGame.KnownItems.Find(ki => ki.ID == itemMade.Name);
                        newRecipe.Display = i18n.Format("craft_produce_x_from_y", resultingKnownItem.ToString(itemMade), resultingSourceItem.ToString(stepRefs[0]));
                    }
                    else if (step.Name == "train")
                    {
                        newRecipe.Actions.Add(new CraftTrainAction()
                        {
                            Trainee = carrier, Target = step
                        });
                    }
                }
                if (newRecipe.Display.IsBlank())
                {
                    continue;
                }
                if (results.Exists(x => x.Display == newRecipe.Display))
                {
                    continue;
                }
                results.Add(newRecipe);
            }

            //Find dyes
            foreach (var maybeDye in ItemsToWorkWith.Tokens)
            {
                var knownItem = NoxicoGame.KnownItems.Find(ki => ki.ID == maybeDye.Name);
                if (knownItem == null)
                {
                    Program.WriteLine("Crafting: don't know what a {0} is.", maybeDye.Name);
                    continue;
                }

                if (knownItem.HasToken("dye"))
                {
                    var dyeItem = maybeDye;
                    var color   = dyeItem.GetToken("color").Text;
                    foreach (var carriedItem in ItemsToWorkWith.Tokens)
                    {
                        knownItem = NoxicoGame.KnownItems.Find(ki => ki.ID == carriedItem.Name);
                        if (knownItem == null)
                        {
                            Program.WriteLine("Crafting: don't know what a {0} is.", carriedItem.Name);
                            continue;
                        }

                        if (knownItem.HasToken("colored") && !knownItem.HasToken("dye"))
                        {
                            var newRecipe = new Recipe();
                            newRecipe.Display = i18n.Format("craft_dye_x_y", knownItem.ToString(carriedItem), color);
                            if (!carriedItem.HasToken("color"))
                            {
                                newRecipe.Actions.Add(new CraftAddTokenAction()
                                {
                                    Target = carriedItem, Add = new Token("color", 0, color)
                                });
                            }
                            else if (carriedItem.GetToken("color").Text == color)
                            {
                                continue;
                            }
                            else
                            {
                                newRecipe.Actions.Add(new CraftChangeTokenAction()
                                {
                                    Target = carriedItem.GetToken("color"), NewText = color, NewValue = 0
                                });
                            }
                            results.Add(newRecipe);
                        }
                    }
                }
            }
            return(results);
        }
コード例 #27
0
ファイル: Introduction.cs プロジェクト: klorpa/Noxico
        /// <summary>
        /// Generic Subscreen handler.
        /// </summary>
        public static void TitleHandler()
        {
            var host = NoxicoGame.HostForm;

            if (Subscreens.FirstDraw)
            {
                Subscreens.FirstDraw = false;
                host.Clear();
                var xScale = Program.Cols / 80f;
                var yScale = Program.Rows / 25f;

                var background   = new Bitmap(Program.Cols, Program.Rows * 2, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                var logo         = Mix.GetBitmap("logo.png");
                var titleOptions = Mix.GetFilesWithPattern("titles\\*.png");
                var chosen       = Mix.GetBitmap(titleOptions.PickOne());
                //Given our random backdrop and fixed logo, draw them both onto background
                //because we can't -just- display alpha-blended PNGs.
                using (var gfx = Graphics.FromImage(background))
                {
                    gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    gfx.Clear(Color.Black);
                    gfx.DrawImage(chosen, 0, 0, Program.Cols, Program.Rows * 2);
                    gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                    gfx.DrawImage(logo, 0, 0, logo.Width * xScale, logo.Height * yScale);
                }
                UIManager.Initialize();
                titleBack = new UIPNGBackground(background);

                var subtitleLeft = (int)(10 * xScale);
                var subtitleTop  = (int)((logo.Height * yScale) / 2) + 1;

                var subtitle   = i18n.GetString("ts_subtitle");
                var pressEnter = "\xC4\xC4\xC4\xC4\xB4 " + i18n.GetString("ts_pressentertobegin") + " <cGray>\xC3\xC4\xC4\xC4\xC4";
                titleCaption = new UILabel(subtitle)
                {
                    Top = subtitleTop, Left = subtitleLeft + 2, Foreground = Color.Teal, Darken = true
                };
                titlePressEnter = new UILabel(pressEnter)
                {
                    Top = subtitleTop + 2, Left = subtitleLeft, Foreground = Color.Gray, Darken = true
                };
                UIManager.Elements.Add(titleBack);
                UIManager.Elements.Add(titleCaption);
                UIManager.Elements.Add(titlePressEnter);
                //UIManager.Elements.Add(new UILabel("\u015c") { Top = 6, Left = 50, Foreground = Color.Gray });
                UIManager.Draw();
                Options.FromTitle = true;
            }
            if (NoxicoGame.IsKeyDown(KeyBinding.Accept) || Subscreens.Mouse || Vista.Triggers != 0)
            {
                if (Subscreens.Mouse)
                {
                    Subscreens.UsingMouse = true;
                }
                Subscreens.Mouse     = false;
                Subscreens.FirstDraw = true;
                var rawSaves = Directory.GetDirectories(NoxicoGame.SavePath);
                var saves    = new List <string>();
                //Check each possible save's version.
                foreach (var s in rawSaves)
                {
                    var verCheck = Path.Combine(s, "version");
                    if (!File.Exists(verCheck))
                    {
                        continue;
                    }
                    var version = int.Parse(File.ReadAllText(verCheck));
                    if (version < 20)
                    {
                        continue;
                    }
                    if (File.Exists(Path.Combine(s, "global.bin")))
                    {
                        saves.Add(s);
                    }
                }
                NoxicoGame.ClearKeys();
                Subscreens.Mouse = false;
                //Linq up a set of options for each save game. This returns the game's names as the keys.
                var options = saves.ToDictionary(new Func <string, object>(s => Path.GetFileName(s)), new Func <string, string>(s =>
                {
                    string p;
                    var playerFile = Path.Combine(s, "player.bin");
                    if (File.Exists(playerFile))
                    {
                        using (var f = new BinaryReader(File.OpenRead(playerFile)))
                        {
                            p = Player.LoadFromFile(f).Character.Name.ToString(true);
                        }
                        return(i18n.Format("ts_loadgame", p, Path.GetFileName(s)));
                    }
                    return(i18n.Format("ts_startoverinx", Path.GetFileName(s)));
                }));
                options.Add("~", i18n.GetString("ts_startnewgame"));
                options.Add("~~", i18n.GetString("ts_testingarena"));
                options.Add("~~~", i18n.GetString("ts_options"));
                //Display our list of saves.
                MessageBox.List(saves.Count == 0 ? i18n.GetString("ts_welcometonoxico") : i18n.GetString(saves.Count == 1 ? "ts_thereisasave" : "ts_therearesaves"), options,
                                () =>
                {
                    if ((string)MessageBox.Answer == "~")
                    {
                        //Restore our title screen backdrop, since the MessageBox subscreen purged it.
                        UIManager.Elements.Add(titleBack);
                        UIManager.Elements.Add(titleCaption);
                        UIManager.Elements.Add(titlePressEnter);
                        UIManager.Draw();
                        MessageBox.Input("What name would you like for your new world?",
                                         NoxicoGame.RollWorldName(),
                                         () =>
                        {
                            NoxicoGame.WorldName = (string)MessageBox.Answer;
                            NoxicoGame.Mode      = UserMode.Subscreen;
                            NoxicoGame.Subscreen = Introduction.CharacterCreator;
                            NoxicoGame.Immediate = true;
                        }
                                         );
                    }
                    else if ((string)MessageBox.Answer == "~~")
                    {
                        NoxicoGame.WorldName = "<Testing Arena>";
                        var env = Lua.Environment;
                        Lua.RunFile("testarena.lua");
                        var testBoard = new Board(env.TestArena.ArenaWidth, env.TestArena.ArenaHeight);
                        var me        = NoxicoGame.Me;
                        me.Boards.Add(testBoard);
                        me.CurrentBoard = testBoard;
                        me.CreatePlayerCharacter(env.TestArena.Name, env.TestArena.BioGender, env.TestArena.IdentifyAs, env.TestArena.Preference, env.TestArena.Bodyplan, new Dictionary <string, string>(), env.TestArena.BonusTrait);
                        env.BuildTestArena(testBoard);
                        me.Player.ParentBoard = testBoard;
                        testBoard.EntitiesToAdd.Add(me.Player);
                        NoxicoGame.InGameTime = new DateTime(740 + Random.Next(0, 20), 6, 26, 12, 0, 0);
                        testBoard.UpdateLightmap(null, true);
                        testBoard.AimCamera();
                        testBoard.Redraw();
                        testBoard.Draw();
                        Options.FromTitle    = false;
                        Subscreens.FirstDraw = true;
                        NoxicoGame.Immediate = true;
                        NoxicoGame.AddMessage(i18n.GetString("welcometest"), Color.Yellow);
                        NoxicoGame.AddMessage(i18n.GetString("rememberhelp"));
                        NoxicoGame.Mode = UserMode.Walkabout;
                    }
                    else if ((string)MessageBox.Answer == "~~~")
                    {
                        Options.FromTitle = true;
                        //Restore our title screen backdrop, since the MessageBox subscreen purged it.
                        UIManager.Initialize();
                        UIManager.Elements.Add(titleBack);
                        UIManager.Elements.Add(titleCaption);
                        UIManager.Elements.Add(titlePressEnter);
                        Options.Open();
                    }
                    else
                    {
                        Options.FromTitle    = false;
                        NoxicoGame.WorldName = (string)MessageBox.Answer;
                        host.Noxico.LoadGame();
                        NoxicoGame.Me.CurrentBoard.Draw();
                        Subscreens.FirstDraw = true;
                        NoxicoGame.Immediate = true;
                        NoxicoGame.AddMessage(i18n.GetString("welcomeback"), Color.Yellow);
                        NoxicoGame.AddMessage(i18n.GetString("rememberhelp"));
                        //TextScroller.LookAt(NoxicoGame.Me.Player);
                        NoxicoGame.Mode = UserMode.Walkabout;
                    }
                }
                                );
            }
        }
コード例 #28
0
 static Descriptions()
 {
     descTable = new TokenCarrier();
     descTable.Tokens.AddRange(Mix.GetTokenTree("bodyparts.tml"));
 }