Esempio n. 1
0
        //private int IndexOf(TimeGetter timeGetter, double time, int startIndex, int endIndex, bool findBackward, int indexIfRepeat)
        //{
        //    if (endIndex - startIndex <= 1)
        //    {
        //        double startTime = timeGetter.GetTime(startIndex);
        //        if (startTime == time)
        //            return startIndex;
        //        if (time < startTime)
        //            return -1;
        //        double endTime = timeGetter.GetTime(endIndex);
        //        if (endTime == time)
        //            return endIndex;
        //        if (time > endTime)
        //            return -1;
        //        if (findBackward)
        //            return startIndex;
        //        return endIndex;
        //    }
        //    int currentIndex = (endIndex + startIndex) / 2;
        //    double currentTime = timeGetter.GetTime(currentIndex);
        //    if (currentTime == time)
        //        return currentIndex;
        //    if (currentTime > time)
        //    {
        //        return IndexOf(timeGetter, time, startIndex, currentIndex, findBackward, indexIfRepeat);
        //    }
        //    else
        //    {
        //        return IndexOf(timeGetter, time, currentIndex, endIndex, findBackward, indexIfRepeat);
        //    }
        //}

        private int FindRepeatIndex(TimeGetter timeGetter, int index, bool findBackward, int indexIfRepeat)
        {
            //if (findBackward)
            //{
            //    int endIndex = FindEndRepeatIndex(timeGetter, index, findBackward);
            //    int firstIndex = FindFirstRepeatIndex(timeGetter, index, findBackward);
            //    int resultIndex = endIndex - indexIfRepeat;
            //    if (resultIndex > firstIndex)
            //        return resultIndex;
            //    return firstIndex;
            //}
            //else
            //{
            //    int endIndex = FindEndRepeatIndex(timeGetter, index, findBackward);
            //    int firstIndex = FindFirstRepeatIndex(timeGetter, index, findBackward);
            //    int resultIndex = firstIndex + indexIfRepeat;
            //    if (resultIndex < endIndex)
            //        return resultIndex;
            //    return endIndex;
            //}

            int endIndex    = FindEndRepeatIndex(timeGetter, index, findBackward);
            int firstIndex  = FindFirstRepeatIndex(timeGetter, index, findBackward);
            int resultIndex = firstIndex + indexIfRepeat;

            if (resultIndex < endIndex)
            {
                return(resultIndex);
            }
            return(endIndex);
        }
Esempio n. 2
0
        void openPanel(Form Panel, string Tittle, object sender)
        {
            //Muestra/Oculta el boton para cerrar ventana
            if ((Button)sender == this.btnClosePanel || (Button)sender == null)
            {
                btnClosePanel.Visible = false;
                lblDate.Visible       = false;
                lblHour.Visible       = false;
                TimeGetter.Stop();
            }
            else
            {
                btnClosePanel.Visible = true;
                lblDate.Visible       = true;
                lblHour.Visible       = true;
                TimeGetter.Start();
            }
            this.lblTitle.Text = Tittle;

            //Abre nueva ventana en el panel contenedor
            if (this.containerPanel.Controls.Count > 0)
            {
                DisposeSon();
            }

            Son          = Panel as Form;
            Son.TopLevel = false;
            Son.Dock     = DockStyle.Fill;
            this.containerPanel.Controls.Add(Son);
            this.containerPanel.Tag = Son;
            Son.Show();
        }
Esempio n. 3
0
        /// <summary>
        /// Checks whether this ship has arrived at its destination and updates status variables, if it has.
        /// Basically this is the "time has passed, check if you are there yet" event.
        /// </summary>
        public void UpdateTravelStatus()
        {
            //If the launch date is null, the ship is currently docked - nothing to do
            if (LaunchDate == null)
            {
                return;
            }
            //Otherwise the ship is on its way
            else
            {
                //Calculate the distance already covered
                var currentStar = db.Stars.Single(i => i.Id == CurrentStarId);
                var targetStar  = db.Stars.Single(i => i.Id == TargetStarId);

                double distanceBetweenStars = DistanceCalculator.GetDistance(currentStar.X.Value, currentStar.Y.Value, targetStar.X.Value, targetStar.Y.Value);
                double distanceTraveled     = SpeedInLightYearsPerMinute * (TimeGetter.GetLocalTime() - LaunchDate.Value).TotalMinutes;

                //If the ship is still en route, nothing to do
                if (distanceTraveled < distanceBetweenStars)
                {
                    return;
                }
                //The ship has arrived - update status
                else
                {
                    CurrentStarId = TargetStarId;
                    LaunchDate    = null;
                    TargetStarId  = null;
                    db.SubmitChanges();
                }
            }
        }
Esempio n. 4
0
    static void Timers()
    {
        var timeGetter = new TimeGetter();

        timeGetter.GetTimeZone();
        timeGetter.Alarm();
    }
Esempio n. 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="timeGetter"></param>
        /// <param name="time"></param>
        /// <param name="findBackward"></param>
        /// <param name="indexIfRepeat"></param>
        /// <returns></returns>
        public int IndexOf(TimeGetter timeGetter, double time, bool findBackward, int indexIfRepeat)
        {
            int    startIndex = 0;
            int    endIndex   = timeGetter.Count - 1;
            double ctime      = timeGetter.GetTime(startIndex);

            if (time < ctime)
            {
                return(-1);
            }
            return(IndexOf(timeGetter, time, 0, endIndex, findBackward, indexIfRepeat));
        }
Esempio n. 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="timeGetter"></param>
        /// <param name="time"></param>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        /// <param name="findBackward"></param>
        /// <param name="indexIfRepeat"></param>
        /// <returns></returns>
        private int IndexOf(TimeGetter timeGetter, double time, int startIndex, int endIndex, bool findBackward, int indexIfRepeat)
        {
            if (findBackward && time > timeGetter.GetTime(timeGetter.Count - 1))
            {
                return(timeGetter.Count - 1);
            }
            if (!findBackward && time < timeGetter.GetTime(0))
            {
                return(0);
            }
            if (endIndex - startIndex <= 1)
            {
                double startTime = timeGetter.GetTime(startIndex);
                if (startTime == time)
                {
                    return(FindRepeatIndex(timeGetter, startIndex, findBackward, indexIfRepeat));
                }
                if (time < startTime)
                {
                    return(-1);
                }
                double endTime = timeGetter.GetTime(endIndex);
                if (endTime == time)
                {
                    return(FindRepeatIndex(timeGetter, endIndex, findBackward, indexIfRepeat));
                }
                if (time > endTime)
                {
                    return(-1);
                }
                return(findBackward ? startIndex : endIndex);
                //if (findBackward)
                //    return FindRepeatIndex(timeGetter, startIndex, findBackward, indexIfRepeat);
                //return FindRepeatIndex(timeGetter, endIndex, findBackward, indexIfRepeat);
            }
            int    currentIndex = (endIndex + startIndex) / 2;
            double currentTime  = timeGetter.GetTime(currentIndex);

            if (currentTime == time)
            {
                return(FindRepeatIndex(timeGetter, currentIndex, findBackward, indexIfRepeat));
            }
            if (currentTime > time)
            {
                return(IndexOf(timeGetter, time, startIndex, currentIndex, findBackward, indexIfRepeat));
            }
            else
            {
                return(IndexOf(timeGetter, time, currentIndex, endIndex, findBackward, indexIfRepeat));
            }
        }
        protected void CreatePilotButton_Click(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("/AccountLogin.aspx?ReturnUrl=" + Request.Url.PathAndQuery);
            }

            AndromedaDataContext db = new AndromedaDataContext();

            if (db.Players.Any(i => i.PlayerName == User.Identity.Name))
            {
                Response.Redirect("Map.aspx");                                                          //Avoid duplicates
            }
            Random rnd = new Random((int)DateTime.Now.Ticks);

            //Create the player
            var player = new Player()
            {
                FirstShipGuid = Guid.NewGuid(),
                PlayerMoney   = 5000,
                PlayerName    = User.Identity.Name
            };

            db.Players.InsertOnSubmit(player);

            //Create the user's spaceship.
            //The page will now reload and the UI will automatically update to display the Guid and
            //make the template available for download.
            db.Spaceships.InsertOnSubmit(
                new Spaceship()
            {
                CannonCount       = 0,
                Created           = TimeGetter.GetLocalTime(),
                CurrentStarId     = rnd.Next(0, db.Stars.Count()),
                Deleted           = false,
                DriveCount        = 0,
                LastRaided        = TimeGetter.GetLocalTime(),
                ModificationCount = 0,
                Player            = player,
                PlayerGuid        = player.FirstShipGuid,
                SensorCount       = 0,
                ShieldCount       = 0,
                ShipModel         = 0,
                TransponderCode   = Guid.NewGuid()
            });
            db.SubmitChanges();

            Response.Redirect("RegisterComplete.aspx");
        }
Esempio n. 8
0
        private int FindEndRepeatIndex(TimeGetter timeGetter, int index, bool findBackward)
        {
            double time        = timeGetter.GetTime(index);
            double currentTime = time;

            while (time == currentTime)
            {
                index++;
                if (index >= timeGetter.Count)
                {
                    return(index - 1);
                }
                currentTime = timeGetter.GetTime(index);
            }
            return(index - 1);
        }
Esempio n. 9
0
        private int FindFirstRepeatIndex(TimeGetter timeGetter, int index, bool findBackward)
        {
            double time        = timeGetter.GetTime(index);
            double currentTime = time;

            while (time == currentTime)
            {
                index--;
                if (index < 0)
                {
                    return(0);
                }
                currentTime = timeGetter.GetTime(index);
            }
            return(index + 1);
        }
Esempio n. 10
0
        /// <summary>
        /// 返回一个整型数组的list
        /// 整型数组第一项是日期,第二项是index
        /// </summary>
        /// <param name="timeGetter"></param>
        /// <returns></returns>
        public static List <SplitterResult> Split(TimeGetter timeGetter, ITradingTimeReader_Code tradingSessionReader)
        {
            List <SplitterResult> indeies = new List <SplitterResult>(500);
            double time = timeGetter.GetTime(0);
            int    date = tradingSessionReader.GetTradingDay(time);

            indeies.Add(new SplitterResult(date, 0));
            for (int index = 1; index < timeGetter.Count; index++)
            {
                time = timeGetter.GetTime(index);
                if (tradingSessionReader.IsStartTime(time))
                {
                    date = tradingSessionReader.GetTradingDay(time);
                    indeies.Add(new SplitterResult(date, index));
                }
            }
            return(indeies);
        }
        /// <summary>
        /// If enough time has elapsed since the last increase, increases the stock count for all commodities.
        /// </summary>
        public static void IncreaseCommodityQuantities()
        {
            #region Log update
            bool          shouldBeLogged = false;
            bool          alreadyLogged  = false;
            StockIncrease logEntry       = new StockIncrease()
            {
                Guid      = Guid.Empty,
                Player    = string.Empty,
                Timestamp = TimeGetter.GetLocalTime()
            };
            #endregion

            int exceptionCount = 0;
            try
            {
                if (IncreaseCommodityQuantities_LastRunTime + IncreaseCommodityQuantities_MinimumInterval <= TimeGetter.GetLocalTime())
                {
                    #region Log update
                    shouldBeLogged = true;
                    #endregion
                    IncreaseCommodityQuantities_LastRunTime = TimeGetter.GetLocalTime();

                    var commodityAtStarsIds = db.CommodityAtStars.ToList().Select(i => new { i.Id });

                    //Increase all commodities
                    //All done in separate data contexts to help successfully continue after an optimistic concurrency exception
                    foreach (var commodityAtStarId in commodityAtStarsIds)
                    {
                        try
                        {
                            using (var db2 = DataContextFactory.GetAndromedaDataContext())
                            {
                                var commodityAtStar = db2.CommodityAtStars.Single(i => i.Id == commodityAtStarId.Id);

                                if (commodityAtStar.Stock.Value + commodityAtStar.ProductionRate.Value > commodityAtStar.MaxCapacity)
                                {
                                    commodityAtStar.Stock = commodityAtStar.MaxCapacity;
                                }
                                else
                                {
                                    commodityAtStar.Stock += commodityAtStar.ProductionRate.Value;
                                }

                                db2.SubmitChanges();
                            }
                        }
                        catch
                        {
                            exceptionCount++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                #region Log update
                if (shouldBeLogged)
                {
                    logEntry.Error = ex.ToString();
                    Logger.Log(logEntry);
                    alreadyLogged = true;
                }
                throw ex;
                #endregion
            }
            finally
            {
                #region Log update
                if (shouldBeLogged && !alreadyLogged)
                {
                    logEntry.Error = exceptionCount.ToString() + " exceptions";
                    Logger.Log(logEntry);
                }
                #endregion
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 返回一个整型数组的list
        /// 整型数组第一项是日期,第二项是index
        /// </summary>
        /// <param name="timeGetter"></param>
        /// <returns></returns>
        public static List <SplitterResult> Split(TimeGetter timeGetter)
        {
            double lastTime = timeGetter.GetTime(0);

            if (timeGetter.Count <= 1)
            {
                List <SplitterResult> results = new List <SplitterResult>(1);
                results.Add(new SplitterResult((int)lastTime, 0));
                return(results);
            }
            double time = timeGetter.GetTime(1);

            //算法
            List <SplitterResult> indeies = new List <SplitterResult>(500);
            int  len          = timeGetter.Count;
            int  currentIndex = 0;
            bool hasNight     = IsNight(timeGetter.GetTime(0));
            bool overNight    = false;

            for (int index = 1; index < len; index++)
            {
                time = timeGetter.GetTime(index);

                int date     = (int)time;
                int lastDate = (int)lastTime;

                /*
                 * 四种情况:
                 * 1.无夜盘,直接生成即可:如20100105090000、...
                 * 2.有夜盘,但夜盘不过夜:如20160329210000、...、20160329233000、...、20160330090000
                 * 3.有夜盘,要过夜,不是周末:如20150324210000、...、20150325023000、...、20150325090000
                 * 4.有夜盘,要过夜,而且是周末:如20141226210000、...、20141227023000、...、20141229090000
                 */

                /*
                 * 规则:
                 * 1.夜盘开始,一定是新的一天开始
                 * 2.
                 */

                //夜盘开始,则一定是新的一天开始
                if (IsNightStart(time, lastTime))
                {
                    indeies.Add(new SplitterResult((int)lastTime, currentIndex));
                    overNight    = false;
                    currentIndex = index;
                    hasNight     = true;
                }
                else if (hasNight)
                {
                    if (date != lastDate)
                    {
                        overNight = true;
                    }
                    //对于夜盘来说,如果到了第二天,而且时间大于6点,则说明夜盘结束了
                    if (overNight && (time - (int)time) > 0.06)
                    {
                        hasNight = false;
                    }
                }
                //只要过了夜都算第二天的
                else if (date != lastDate)
                {
                    indeies.Add(new SplitterResult((int)lastTime, currentIndex));
                    currentIndex = index;
                    overNight    = false;
                }

                lastTime = time;
            }

            //如果最后一个时间是晚上
            int endDate = (int)lastTime;

            if (IsNight(lastTime))
            {
                endDate += 1;
            }

            indeies.Add(new SplitterResult(endDate, currentIndex));
            return(indeies);
        }
Esempio n. 13
0
 public static List <SplitterResult> Split(TimeGetter timeGetter, ITradingDayReader openDateReader)
 {
     return(Split(timeGetter));
 }
Esempio n. 14
0
        public static Option Parking()
        {
            ConsoleWriter.ClearScreen();

            var lines     = File.ReadAllLines(@"UI/maps/7.Parking.txt");
            var drawables = TextEditor.Add.DrawablesAt(lines, 0);

            TextEditor.Center.ToScreen(drawables, Console.WindowWidth, Console.WindowHeight);
            var selectionList = new SelectionList <Option>(ConsoleColor.Green, '$');

            selectionList.GetCharPositions(drawables);
            selectionList.AddSelections(new[]
            {
                Option.PurchaseTicket,
                Option.ReEnterhours,
                Option.Account
            });

            var drawProps      = drawables.FindAll(x => x.Chars == "¤");
            var props          = drawProps.Select(x => (x.CoordinateX, x.CoordinateY)).ToList();
            var parkFromXY     = props[0];
            var pricePerHourXY = props[1];
            var shipLengthXY   = props[2];

            var calculatedPriceXY = props[3];
            var enterHoursXY      = props[4];
            var receiptXY         = props[5];
            var openNext          = DatabaseManagement.ParkingManagement.CheckParkingStatus();

            Console.ForegroundColor = ConsoleColor.Green;
            LineTools.SetCursor(parkFromXY);

            if (openNext.isOpen)
            {
                Console.Write("Now");
            }
            else
            {
                Console.Write(openNext.nextAvailable);
            }

            LineTools.SetCursor(pricePerHourXY);
            Console.Write(DatabaseManagement.ParkingManagement.CalculatePrice(_account.SpaceShip, 1) * 60);
            LineTools.SetCursor(shipLengthXY);
            Console.Write(_account.SpaceShip.ShipLength);

            ConsoleWriter.TryAppend(drawables.Except(drawProps).ToList());
            ConsoleWriter.Update();

            Option menuSel;
            double hours;


            var timeGetter = new TimeGetter(enterHoursXY, calculatedPriceXY, 10000,
                                            DatabaseManagement.ParkingManagement.CalculatePrice);

            if (openNext.isOpen == false)
            {
                Console.ReadKey(true);
                return(Option.Account);
            }

            do
            {
                hours   = timeGetter.GetMinutes(_account.SpaceShip);
                menuSel = selectionList.GetSelection();

                if (menuSel == Option.PurchaseTicket && hours == 0)
                {
                    menuSel = Option.ReEnterhours;
                }
            } while (menuSel == Option.ReEnterhours);

            if (Option.PurchaseTicket == menuSel)
            {
                ConsoleWriter.ClearScreen();

                var receipt = DatabaseManagement.ParkingManagement.SendInvoice(_account, hours);
                var boxData = new BoxData((Console.WindowWidth / 2 - 10, parkFromXY.CoordinateY));
                boxData.Update(new[] { "Loading receipt..." });

                string[] receiptString =
                {
                    "Purchase successful!",
                    "",
                    "Ticket Holder: " + receipt.Account.AccountName,
                    "Start time: " + receipt.StartTime,
                    "End time: " + receipt.EndTime,
                    "Price: " + receipt.Price
                };
                boxData.Update(receiptString);

                Console.ReadKey(true);
            }

            return(Option.Account);
        }
Esempio n. 15
0
        protected void TeleportPilotButton_Click(object sender, EventArgs e)
        {
            AndromedaDataContext db = new AndromedaDataContext();

            if (!User.Identity.IsAuthenticated)
            {
                return;                                 //Avoid unauthenticated users
            }
            if (!db.Players.Any(i => i.PlayerName == User.Identity.Name))
            {
                return;                                                           //There must be a player
            }
            #region Log update
            bool      alreadyLogged = false;
            PilotWarp logEntry      = new PilotWarp()
            {
                Player    = User.Identity.Name,
                Timestamp = DateTime.Now
            };
            #endregion

            Random rnd = new Random((int)DateTime.Now.Ticks);

            try
            {
                var player = db.Players.Single(i => i.PlayerName == User.Identity.Name);
                #region Log update
                logEntry.Guid = player.FirstShipGuid.Value;
                #endregion

                foreach (var spaceship in player.Spaceships)
                {
                    if (spaceship.DebugTimestamp != null && spaceship.DebugTimestamp.Value.Add(TimeSpan.FromHours(48)) > TimeGetter.GetLocalTime())
                    {
                        throw new Exception("Az űrhajó még nem teleportálható!");
                    }
                    else
                    {
                        var stars = db.Stars.Where(i => i.Id != spaceship.CurrentStarId).ToList();

                        var newStar = stars[rnd.Next(0, stars.Count)];

                        spaceship.CurrentStarId  = newStar.Id;
                        spaceship.LaunchDate     = null;
                        spaceship.TargetStarId   = null;
                        spaceship.DebugTimestamp = TimeGetter.GetLocalTime();

                        db.SubmitChanges();
                    }
                }

                Response.Redirect("Map.aspx"); //Make the browser throw away the submitted POST so that a F5 does not repeat the Reset Pilot command
            }
            catch (Exception ex)
            {
                #region Log update
                logEntry.Error = ex.ToString();
                Logger.Log(logEntry);
                alreadyLogged = true;
                //throw ex; WARNING THIS IS NOT USUALLY RESET
                #endregion
            }
            finally
            {
                #region Log update
                if (!alreadyLogged)
                {
                    logEntry.Error = "";
                    Logger.Log(logEntry);
                }
                #endregion
            }
        }
Esempio n. 16
0
        protected void ResetPilotButton_Click(object sender, EventArgs e)
        {
            AndromedaDataContext db = new AndromedaDataContext();

            if (!User.Identity.IsAuthenticated)
            {
                return;                                 //Avoid unauthenticated users
            }
            if (!db.Players.Any(i => i.PlayerName == User.Identity.Name))
            {
                return;                                                           //There must be an old ship
            }
            #region Log update
            bool       alreadyLogged = false;
            PilotReset logEntry      = new PilotReset()
            {
                Player    = User.Identity.Name,
                Timestamp = DateTime.Now
            };
            #endregion

            Random rnd = new Random((int)DateTime.Now.Ticks);

            try
            {
                //Get player
                var player = db.Players.Single(i => i.PlayerName == User.Identity.Name);
                #region Log update
                logEntry.Guid = player.FirstShipGuid.Value;
                #endregion

                //Set player
                player.PlayerMoney = 5000;

                //Take old ships out of commission by taking it away from the player and assigning it a new GUID
                //Since all other resources reference the ship by ID (not GUID), all other resources will be decommissioned as well
                foreach (var oldSpaceship in player.Spaceships)
                {
                    oldSpaceship.PlayerGuid = Guid.NewGuid(); //Guid changed to make the ship un-controllable
                    oldSpaceship.Deleted    = true;           //This will hide the ship from the map
                }
                player.Spaceships.Clear();

                //Create the user's new spaceship with the old GUID.
                //The page will now reload and the UI will automatically update to display the Guid and
                //make the template available for download.
                db.Spaceships.InsertOnSubmit(
                    new Spaceship()
                {
                    PlayerGuid        = player.FirstShipGuid,
                    DriveCount        = 0,
                    SensorCount       = 0,
                    CurrentStarId     = rnd.Next(0, db.Stars.Count()),
                    Deleted           = false,
                    ModificationCount = 0,
                    ShipModel         = 0,
                    CannonCount       = 0,
                    ShieldCount       = 0,
                    LastRaided        = TimeGetter.GetLocalTime(),
                    Created           = TimeGetter.GetLocalTime(),
                    TransponderCode   = Guid.NewGuid(),
                    Player            = player,
                });
                db.SubmitChanges();

                Response.Redirect("Map.aspx"); //Make the browser throw away the submitted POST so that a F5 does not repeat the Reset Pilot command
            }
            catch (Exception ex)
            {
                #region Log update
                logEntry.Error = ex.ToString();
                Logger.Log(logEntry);
                alreadyLogged = true;
                throw ex;
                #endregion
            }
            finally
            {
                #region Log update
                if (!alreadyLogged)
                {
                    logEntry.Error = "";
                    Logger.Log(logEntry);
                }
                #endregion
            }
        }
Esempio n. 17
0
 /// <summary>
 /// 得到timeGetter里time对应的索引号,如果没有该时间,根据findBackward找到对应时间
 /// </summary>
 /// <param name="timeGetter"></param>
 /// <param name="time"></param>
 /// <param name="findBackward"></param>
 /// <returns></returns>
 public int IndexOf(TimeGetter timeGetter, double time, bool findBackward)
 {
     return(IndexOf(timeGetter, time, findBackward, 0));
 }
Esempio n. 18
0
 /// <summary>
 /// 得到timeGetter里time对应的索引号
 /// </summary>
 /// <param name="timeGetter"></param>
 /// <param name="time"></param>
 /// <returns></returns>
 public int IndexOf(TimeGetter timeGetter, double time)
 {
     return(IndexOf(timeGetter, time, true));
 }