Exemplo n.º 1
0
        public static void LoadItems()
        {
            foreach (Quality q in Enum.GetValues(typeof(Quality)))
            {
                _lootLibrary.Add(new List <LootItem>());
            }

            // Parse the loot
            foreach (string path in Settings.itemsXmlPaths)
            {
                List <ItemBuilder> parsedItems = XmlManager.ParseItems(path);
                foreach (ItemBuilder parsedItem in parsedItems)
                {
                    //_lootLibrary.Add(parsedItem);
                    if (parsedItem.itemClass == ItemClass.Loot)
                    {
                        Add(parsedItem.rarity, parsedItem.name, parsedItem.abilityId);
                    }
                }
                if (parsedItems.Count > 0)
                {
                    ConsoleEx.Log("Successfully parsed " + parsedItems.Count + " item(s) in " + path.Substring(path.LastIndexOf("/") + 1));
                }
                else
                {
                    ConsoleEx.Log("No valid items found in " + path.Substring(path.LastIndexOf("/") + 1));
                }
            }
        }
Exemplo n.º 2
0
        public static void WebThread()
        {
            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            listener.Prefixes.Add("http://*:80/");
            listener.Prefixes.Add("https://*:443/");
            try
            {
                listener.Start();
                ConsoleEx.Log("Listening...");
            }
            catch (HttpListenerException ex)
            {
                if (ex.ErrorCode == 5)
                {
                    ConsoleEx.Log("Access denied on socket bind. Please launch the app with administrator "
                                  + "priviledges to enable web functionality");
                    return;
                }
            }

            while (listener.IsListening && threadState != ThreadState.Stopping)
            {
                var          callback = new AsyncCallback(ListenerCallback);
                IAsyncResult result   = listener.BeginGetContext(callback, listener);
                result.AsyncWaitHandle.WaitOne();
                //System.Threading.Thread.Sleep(1);
            }
            if (listener.IsListening)
            {
                listener.Stop();
            }
        }
Exemplo n.º 3
0
 public static void ThreadMain()
 {
     while (threadState != ThreadState.Stopping)
     {
         List <PlayerResponsePair> servedPlayers = new List <PlayerResponsePair>();
         // Serving
         foreach (PlayerResponsePair data in waitingPlayers)
         {
             if (data.player.isWaitingForUpdate)
             {
                 WebWriter.Reply(data.response, WebConstructor.GetShipLog(data.player.ship));
                 data.player.NotifyOnFlush();
                 servedPlayers.Add(data);
             }
         }
         if (servedPlayers.Count > 0)
         {
             ConsoleEx.Log("Served updates to " + servedPlayers.Count + " player(s).");
         }
         // Cleaning up
         foreach (PlayerResponsePair data in servedPlayers)
         {
             waitingPlayers.Remove(data);
         }
         // Waiting
         System.Threading.Thread.Sleep(1000);
     }
 }
Exemplo n.º 4
0
 public static void LoadEvents()
 {
     Add(EventGroup.SpaceSector, "Прогулива{g:-лся|-лась} по кораблю медленным шагом, раздумывая о бесконечности жизни.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Захотелось проверить, а будет ли работать корабль на биотопливе, но под рукой не нашлось ни одного биологического существа. Кроме меня.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Случайно замети{g:-л|-ла}, как космический патруль проскочил мимо меня. Интересно, это меня они не увидели, или нет?", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Почувствовав, как живот урчит от голода, захотелось проверить запасы провианта. Уж лучше бы этого не дела{g:-л|-ла}.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Проходя мимо панели управления кораблем, услыша{g:-л|-ла} странный сигнал из радиоприемника. То ли со мной пытаются выйти на связь другие расы, то ли просто механизм неисправен.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Увиде{g:-л|-ла} за иллюминатором сгорающие метероиды. Помоли{g:-лся|-лась}, чтобы они пролетели мимо.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Иногда мне кажется, что корабль за мной следит. Возможно, стоит навестить врача.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Внезапно просну{g:-лся|-лась} от невыносимой жары. Как выяснилось, мы едва обогнули какую-то звезду. Не знаю, радоваться жизни или плакать от будущих затрат на починку.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Люблю безграничные просторы Вселенной – кто знает, куда в следующий раз пошлет тебя судьба или космический патруль?", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "От безделья и скуки нача{g:-л|-ла} плевать в потолок. Невесомость – вещь серьезная.", null, EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Наш{g:-ел|-ла} {lootItemA} прямо на полу. Вот удача!", Reward.AsLoot(Quality.Legendary, 1), EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Несмотря на то, что {lootItemA}, {lootItemB}, {lootItemC} и {lootItemD} я получи{g:-л|-ла} совершенно случайно, я совсем не против!", Reward.AsLoot(Quality.Common, 4), EventFilters.StoryCompleted(StoryStage.ShipExploration));
     Add(EventGroup.SpaceSector, "Исследование корабля", Reward.AsStoryProgress(StoryStage.Completed), EventFilters.StoryRequired(StoryStage.ShipExploration));
     Add(EventGroup.InTravel, "Полет 01");
     Add(EventGroup.InTravel, "Полет 02");
     Add(EventGroup.InTravel, "Полет 03");
     Add(EventGroup.InTravel, "Полет 04");
     Add(EventGroup.InTravel, "Полет 05");
     Add(EventGroup.InTravel, "Полет 06");
     Add(EventGroup.InTravel, "Полет 07");
     Add(EventGroup.InTravel, "Полет 08");
     Add(EventGroup.InTravel, "Полет 09");
     Add(EventGroup.InTravel, "Полет 10");
     Add(EventGroup.Station, "Станция. Отдых.", Reward.AsStamina(50));
     Add(EventGroup.Station, "Станция. Отдых 2.", Reward.AsStamina(50));
     Add(EventGroup.Station, "Станция. Отдых 3.", Reward.AsStamina(50));
     Add(EventGroup.Station, "Станция. Читаем журналы.", Reward.AsCuriosity(50));
     Add(EventGroup.Station, "Станция. Читаем журналы 2.", Reward.AsCuriosity(50));
     Add(EventGroup.Station, "Станция. Читаем журналы 3.", Reward.AsCuriosity(50));
     Add(EventGroup.Planet, "{planetName}. Немного устал{g:|-а}.", Reward.AsStamina(-25));
     Add(EventGroup.Planet, "{planetName}. Очень устал{g:|-а}.", Reward.AsStamina(-50));
     Add(EventGroup.Planet, "{planetName}. Тут скучно.", Reward.AsCuriosity(-25));
     Add(EventGroup.Planet, "{planetName}. Очень скучно.", Reward.AsCuriosity(-50));
     Add(EventGroup.Planet, "{planetName}. Ничего интересного.");
     Add(EventGroup.Planet, "Ничего тут нет.");
     Add(EventSpecial.OnLevelUp, "Ура! Я ещё на один уровень ста{g:-л|-ла} ближе к смерти!");
     AddByLink(EventGroup.SpaceSector, "newPilot", Reward.AsStoryProgress(StoryStage.ShipExploration), EventFilters.StoryRequired(StoryStage.Initial));
     Add(EventSpecial.OnTravelStart, "Поехали! Цель - {planetNameLong}.");
     Add(EventSpecial.OnPlanetArrival, "Вот она, {planetName}! Правда, ничего не видно, стекла запотели немного.");
     ConsoleEx.Log("Successfully created " + library.Count + " native event(s)");
     foreach (string path in Settings.eventsXmlPaths)
     {
         List <EventBuilder> parsedEvents = XmlManager.ParseEvents(path);
         foreach (EventBuilder parsedEvent in parsedEvents)
         {
             library.Add((Event)parsedEvent);
         }
         if (parsedEvents.Count > 0)
         {
             ConsoleEx.Log("Successfully parsed " + parsedEvents.Count + " event(s) in " + path.Substring(path.LastIndexOf("/") + 1));
         }
         else
         {
             ConsoleEx.Log("No valid events found in " + path.Substring(path.LastIndexOf("/") + 1));
         }
     }
 }
Exemplo n.º 5
0
 public static void ThreadMain()
 {
     //ConsoleWindow window = new ConsoleWindow();
     //window.ShowDialog();
     consoleWindow = new ConsoleWindow();
     System.Windows.Forms.Application.Run(consoleWindow);
     ConsoleEx.Log("Graphical console closed");
     Core.Shutdown();
 }
Exemplo n.º 6
0
        public static void ListenerCallback(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                HttpListenerRequest request  = context.Request;
                // Obtain a response object.
                HttpListenerResponse response = context.Response;
                // Construct a response.
                string requestedPage = "";
                foreach (string s in request.Url.Segments)
                {
                    requestedPage += s;
                }
                if (requestedPage == "/")
                {
                    requestedPage = "/index.html";
                }

                ConsoleEx.Log("(" + request.RemoteEndPoint.Address.ToString() + ") " + request.HttpMethod.ToString() + " " + requestedPage);

                if (!request.IsSecureConnection)
                {
                    WebWriter.SendFile(response, "www/forceSSL.html");
                }
                else if (File.Exists("www" + requestedPage))
                {
                    WebWriter.SendFile(response, "www" + requestedPage);
                }
                else
                {
                    if (requestedPage == "/hero")
                    {
                        WebRequest.OnHero(request, response);
                    }
                    else if (requestedPage == "/pilotLog")
                    {
                        WebRequest.OnPilotLog(request, response);
                    }
                    else if (requestedPage == "/register")
                    {
                        WebRequest.OnRegister(request, response);
                    }
                    else if (requestedPage == "/login")
                    {
                        WebRequest.OnLogin(request, response);
                    }
                    else if (requestedPage == "/update")
                    {
                        WebRequest.OnUpdate(request, response);
                    }
                }
            }
            catch (Exception) { }
        }
Exemplo n.º 7
0
        public static void Logout(Player player, string reason)
        {
            if (player == null)
            {
                return;
            }

            player.Logout();
            ConsoleEx.Log("Player " + player.username + " disconnected. Reason: " + reason + ".");
        }
Exemplo n.º 8
0
 private void OnInput(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.Enter && mainInput.Text.Length > 0)
     {
         string cmd = mainInput.Text;
         commandHistory.Add(cmd);
         commandHistoryPos = commandHistory.Count;
         ConsoleEx.Log("> " + cmd);
         CmdParser.Handle(cmd);
         mainInput.Clear();
         e.SuppressKeyPress = true;
         e.Handled          = true;
     }
     else if (e.KeyCode == Keys.Up && commandHistory.Count > 0)
     {
         if (commandHistoryPos > 0)
         {
             commandHistoryPos -= 1;
         }
         mainInput.Text = commandHistory[commandHistoryPos];
         mainInput.Select(mainInput.Text.Length, 0);
         e.SuppressKeyPress = true;
         e.Handled          = true;
     }
     else if (e.KeyCode == Keys.Down)
     {
         if (commandHistoryPos < commandHistory.Count)
         {
             commandHistoryPos += 1;
             if (commandHistoryPos < commandHistory.Count)
             {
                 mainInput.Text = commandHistory[commandHistoryPos];
                 mainInput.Select(mainInput.Text.Length, 0);
             }
             else
             {
                 mainInput.Text = "";
             }
         }
         else
         {
             mainInput.Text = "";
         }
         e.SuppressKeyPress = true;
         e.Handled          = true;
     }
     else
     {
         commandHistoryPos = commandHistory.Count;
     }
 }
Exemplo n.º 9
0
        public static void LoadAccounts()
        {
            List <Player> parsedList = XmlManager.ParseAccounts();

            foreach (Player player in parsedList)
            {
                _playerLibrary.Add(player);
            }
            if (parsedList.Count > 0)
            {
                ConsoleEx.Log("Successfully loaded " + parsedList.Count + " account(s).");
            }
            else
            {
                ConsoleEx.Log("No account database found or it is corrupted.");
            }
        }
Exemplo n.º 10
0
        public Event GetEvent(EventSpecial specialGroup)
        {
            Event e = Destiny.FindEvent(this, specialGroup);

            if (e == null)
            {
                ConsoleEx.Log("ERROR: No event found in destiny. Emptying queue and retrying.");
                blockedEvents.Clear();
                e = Destiny.FindEvent(this, specialGroup);
                if (e == null)
                {
                    ConsoleEx.Log("ERROR: No suitable event. Please check event filters for special event "
                                  + Enum.GetName(typeof(EventSpecial), specialGroup) + ".");
                    return(null);
                }
            }
            return(e);
        }
Exemplo n.º 11
0
        public Event GetEvent(int eventGroup)
        {
            Event e = Destiny.FindEvent(this, eventGroup);

            if (e == null)
            {
                ConsoleEx.Log("ERROR: No event found in destiny. Emptying queue and retrying.");
                blockedEvents.Clear();
                e = Destiny.FindEvent(this, eventGroup);
                if (e == null)
                {
                    ConsoleEx.Log("ERROR: No suitable event. Please check event filters for group id "
                                  + eventGroup + ".");
                    return(null);
                }
            }
            return(e);
        }
Exemplo n.º 12
0
        public static bool CreateAccount(string username, string password, string passwordSalt = null)
        {
            username = username.Replace(" ", "");
            foreach (Player p in _playerLibrary)
            {
                if (p.username == username)
                {
                    ConsoleEx.Error("Account creation error. Username taken: " + username);
                    return(false);
                }
            }
            Player player = new Player(username, password, passwordSalt);

            _playerLibrary.Add(player);
            ConsoleEx.Log("Account " + username + " created successfully.");
            if (autosaveEnabled)
            {
                DiskCore.Enqueue(DiskAction.UpdateAccountDatabase);
            }
            return(true);
        }
Exemplo n.º 13
0
 public static string Login(string username, string password)
 {
     username = username.Replace(" ", "");
     for (int i = 0; i < _playerLibrary.Count; i++)
     {
         if (username == _playerLibrary[i].username)
         {
             if (_playerLibrary[i].CheckPassword(password))
             {
                 ConsoleEx.Log("Player " + _playerLibrary[i].username + " logged in.");
                 return(_playerLibrary[i].Login());
             }
             else
             {
                 ConsoleEx.Error("Login failed. Password mismatch.");
                 return("");
             }
         }
     }
     ConsoleEx.Error("Login failed. User not found.");
     return("");
 }
Exemplo n.º 14
0
        //===============================================================================
        // Account management
        //===============================================================================
        public static void SaveAccounts()
        {
            //StringBuilder output = new StringBuilder();
            MemoryStream output = new MemoryStream();

            bool         savedToTempFile = false;
            StreamWriter file;

            if (File.Exists(Settings.playersXmlPath))
            {
                savedToTempFile = true;
                file            = new StreamWriter(Settings.playersTempXmlPath);
            }
            else
            {
                file = new StreamWriter(Settings.playersXmlPath);
            }
            XmlWriterSettings ws = new XmlWriterSettings();

            ws.Indent      = true;
            ws.IndentChars = "\t";
            ws.Encoding    = Encoding.UTF8;
            XmlWriter writer = XmlWriter.Create(output, ws);

            // Generate an XML
            writer.WriteStartDocument();
            writer.WriteStartElement("root");
            foreach (Player p in Authorization.playerList)
            {
                writer.WriteStartElement("player");

                writer.WriteStartElement("username");
                writer.WriteValue(p.username);
                writer.WriteEndElement();

                writer.WriteStartElement("password");
                writer.WriteValue(p.password);
                writer.WriteEndElement();

                writer.WriteStartElement("passwordSalt");
                writer.WriteValue(p.passwordSalt);
                writer.WriteEndElement();

                writer.WriteStartElement("loginCounter");
                writer.WriteValue(p.loginCounter);
                writer.WriteEndElement();

                writer.WriteStartElement("startingShipName");
                writer.WriteValue(p.startingShipName);
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            output.Position = 0;
            //file.Write(output.Read);
            output.WriteTo(file.BaseStream);
            output.Close();
            output.Dispose();
            file.Close();
            if (savedToTempFile)
            {
                try
                {
                    File.Move(Settings.playersXmlPath, Settings.playersBackupXmlPath);
                    File.Move(Settings.playersTempXmlPath, Settings.playersXmlPath);
                    File.Delete(Settings.playersBackupXmlPath);
                }
                catch (Exception)
                {
                    ConsoleEx.Error("Account database update failed.");
                    return;
                }
            }
            ConsoleEx.Log("Account database updated successfully.");
            //ConsoleEx.Debug(output.ToString());
        }
Exemplo n.º 15
0
 public static void FullReload()
 {
     ConsoleEx.Log("Clearing the event library");
     library.Clear();
     LoadEvents();
 }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            threadLibrary.Add(Thread.CurrentThread, ThreadId.Main);
            LogManager.CleanUpFiles();
            ConsoleEx.Log("Thread started");

            ConsoleEx.Log("Loading strings");
            Localization.Load();

            ConsoleEx.Log("Loading looters");
            Looter.LoadItems();

            ConsoleEx.Log("Loading destiny");
            Destiny.LoadEvents();

            ConsoleEx.Log("Loading planets");
            Terraformer.LoadPlanets();

            ConsoleEx.Log("Loading accounts");
            Authorization.LoadAccounts();

            ConsoleEx.Log("Rolling the dice");
            Random.RollSeed();

            ConsoleEx.Log("Creating the universe");
            Universe.Create();

            ConsoleEx.Log("Generating RSA keys");
            WebSecurity.GenerateKeys();

            ConsoleEx.Log("Collecting command line data");
            CmdParser.Initialize();

            ConsoleEx.Log("Initializing web thread");
            Thread webThread = new Thread(WebCore.WebThread);

            WebCore.OnStart();
            webThread.Start();
            threadLibrary.Add(webThread, ThreadId.Web);

            ConsoleEx.Log("Initializing world thread");
            Thread worldThread = new Thread(WorldCore.WorldThread);

            WorldCore.OnStart();
            worldThread.Start();
            threadLibrary.Add(worldThread, ThreadId.World);

            ConsoleEx.Log("Initializing disk thread");
            Thread diskThread = new Thread(DiskCore.ThreadMain);

            DiskCore.OnStart();
            diskThread.Start();
            threadLibrary.Add(diskThread, ThreadId.Disk);

            ConsoleEx.Log("Initializing update thread");
            Thread updateThread = new Thread(WebUpdaterCore.ThreadMain);

            WebUpdaterCore.OnStart();
            updateThread.Start();
            threadLibrary.Add(updateThread, ThreadId.Update);

            ConsoleEx.Log("Initializing GUI thread");
            Thread guiThread = new Thread(GUICore.ThreadMain);

            GUICore.OnStart();
            guiThread.Start();
            threadLibrary.Add(guiThread, ThreadId.GUI);

            ConsoleEx.Log("Switching to graphical console");
            HideConsole();

            while (state != ThreadState.Stopping)
            {
                Thread.Sleep(1);
            }

            ConsoleEx.Log("Initializing shutdown sequence");

            //ConsoleEx.Log("Switching back to native console");
            //ShowConsole();

            GUICore.OnStop();

            ConsoleEx.Log("Shutting down update thread");
            WebUpdaterCore.OnStop();
            updateThread.Join(1000);
            updateThread.Abort();

            ConsoleEx.Log("Shutting down disk thread");
            DiskCore.OnStop();
            diskThread.Join(1000);
            diskThread.Abort();

            ConsoleEx.Log("Shutting down world thread");
            WorldCore.OnStop();
            worldThread.Join(1000);
            worldThread.Abort();

            ConsoleEx.Log("Shutting down web thread");
            WebCore.OnStop();
            webThread.Join(1000);
            webThread.Abort();

            ConsoleEx.Log("Shutting down main thread");
            ConsoleEx.Log("Goodbye");
        }
Exemplo n.º 17
0
        public static void Handle(string cmd)
        {
            bool          handled = false;
            StringBuilder output  = new StringBuilder();

            // Formatting
            cmd = cmd.ToLower();
            // Basic commands
            switch (cmd)
            {
            case "help":
                output.AppendLine("Available types:");
                foreach (Type t in staticTypes)
                {
                    output.AppendLine("- " + t.Name);
                }
                handled = true;
                break;

            case "event.reload":
                Destiny.FullReload();
                break;

            case "exit":
                ConsoleWindow.CloseInstance();
                handled = true;
                break;
            }
            // Still not handled
            if (!handled && cmd.Substring(0, 1) == "#")
            {
                string reflectionLine = ParseReflectionCommand(cmd.Substring(1));
                if (reflectionLine != null && reflectionLine.Length > 0)
                {
                    output.AppendLine(reflectionLine);
                    handled = true;
                }
                foreach (Type t in staticTypes)
                {
                    // Show all fields and properties

                    /*if (t.Name.ToLower() == cmd.ToLower())
                     * {
                     *  output.AppendLine("Please note that the console functionality is still Work-In-Progress.");
                     *  var fields = t.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
                     *  foreach (FieldInfo field in fields)
                     *  {
                     *      output.AppendLine(field.Name + " = " + Parse(field.GetValue(null), 0));
                     *  }
                     *  var properties = t.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
                     *  foreach (PropertyInfo property in properties)
                     *  {
                     *      output.AppendLine(property.Name + " = " + Parse(property.GetValue(null, null), 0));
                     *  }
                     *  handled = true;
                     *  break;
                     * }*/
                }
            }

            // Unknown
            if (!handled)
            {
                output.AppendLine("Unknown command");
            }
            // Remove last line break
            if (output.Length > 0)
            {
                output.Remove(output.Length - 2, 2);
            }
            // Flush to console
            ConsoleEx.Log(output.ToString(), false);
        }