Exemplo n.º 1
0
        private async Task GetSeasonData()
        {
            var folder = tvwFolder.SelectedNode.Tag.ToString();
            await SeasonHelper.GetEpisodeMetadata(_tvdb, folder).ConfigureAwait(false);

            this.InvokeUI(() => LoadAllFiles(folder));
            SetStatus($"Loaded season metadata for '{folder}'");
        }
        public ActionResult Schedule(int selectedRound = -1)
        {
            using (var ctx = new FootballEntities())
            {
                var actualSeason = SeasonHelper.GetCurrentSeason(DateTime.Today);
                var actualRound  = MatchweekHelper.GetMatchweekToDisplayInSchedule();
                var data         = new List <MainPageModel>();
                if (!(selectedRound >= 1 && selectedRound <= 38))
                {
                    selectedRound = actualRound;
                }
                int success   = 0;
                int notPlayed = 0;

                foreach (var x in ctx.Matches.Where(d => (d.Matchweek == selectedRound) && d.Season.Equals(actualSeason)))
                {
                    if (selectedRound <= actualRound)
                    {
                        var score = ctx.Scores.FirstOrDefault(w => w.MatchId == x.Id);
                        int?homeGoals, awayGoals;
                        if (score != null)
                        {
                            homeGoals = score.HomeGoals;
                            awayGoals = score.AwayGoals;
                            bool rightPredicted = CompareScores((int)homeGoals, (int)awayGoals, x.HomeGoalsPredicted,
                                                                x.AwayGoalsPredicted);
                            if (rightPredicted)
                            {
                                success++;
                            }
                        }
                        else
                        {
                            notPlayed++;
                            homeGoals = null;
                            awayGoals = null;
                        }
                        data.Add(new MainPageModel(x.Team1.FullName, x.Team.FullName, x.HomeGoalsPredicted,
                                                   x.AwayGoalsPredicted, awayGoals, homeGoals, x.Date.Date));
                    }
                    else
                    {
                        data.Add(new MainPageModel(x.Team1.FullName, x.Team.FullName, x.HomeGoalsPredicted, x.AwayGoalsPredicted, null, null, x.Date.Date));
                    }
                }

                ViewBag.actualRound   = actualRound;
                ViewBag.selectedRound = selectedRound;
                if (selectedRound <= actualRound && notPlayed < 10)
                {
                    var successPercent = (success / (10.0 - notPlayed)) * 100.0;
                    ViewBag.success = Math.Round(successPercent, 2);
                }
                return(View(data.Distinct()));
            }
        }
        public void CheckSeasonForDate()
        {
            var jan  = SeasonHelper.GetCurrentSeason(new DateTime(2017, 1, 10));
            var july = SeasonHelper.GetCurrentSeason(new DateTime(2017, 7, 10));
            var nov  = SeasonHelper.GetCurrentSeason(new DateTime(2017, 11, 10));

            Assert.AreEqual(jan, "2016/2017");
            Assert.AreEqual(july, "2017/2018");
            Assert.AreEqual(nov, "2017/2018");
        }
Exemplo n.º 4
0
        private async Task RenameEpisodes()
        {
            var folder       = tvwFolder.SelectedNode.Tag.ToString();
            var seriesFolder = new DirectoryInfo(folder).Parent.FullName;
            var seriesName   = SeriesIOHelper.GetSeriesMetadata(seriesFolder).Series.Title;

            await SeasonHelper.RenameFiles(api : _tvdb, seriesName : seriesName, seasonPath : folder);

            LoadAllFiles(folder);
        }
        private Tuple <int, int, int> GetSuccessRateOfPrediction(TeamsInfoModel model)
        {
            int successScorePredictions  = 0;
            int successResultPredictions = 0;
            int allMatches   = 0;
            var teamName     = model.Team1;
            var actualSeason = SeasonHelper.GetCurrentSeason(DateTime.Today);

            using (var ctx = new FootballEntities())
            {
                var actualRound = MatchweekHelper.GetCurrentMatchweek();
                var teamId      = ctx.Teams.FirstOrDefault(e => e.FullName.Equals(teamName)).Id;

                foreach (var match in ctx.Matches.Where(e => (e.HomeId == teamId || e.AwayId == teamId) &&
                                                        DateTime.Compare(e.Date, DateTime.Today) < 0))
                {
                    var scoreOfMatch = match.Scores.FirstOrDefault();
                    if (scoreOfMatch == null)
                    {
                        continue;
                    }

                    if (!SeasonsComapare(model.SeasonSince, model.SeasonTo, match.Season))
                    {
                        continue;
                    }
                    if (match.AwayGoalsPredicted == null || match.HomeGoalsPredicted == null)
                    {
                        continue;
                    }

                    if ((scoreOfMatch.HomeGoals > scoreOfMatch.AwayGoals &&
                         match.HomeGoalsPredicted > match.AwayGoalsPredicted) ||
                        (scoreOfMatch.HomeGoals < scoreOfMatch.AwayGoals &&
                         match.HomeGoalsPredicted < match.AwayGoalsPredicted) ||
                        (scoreOfMatch.HomeGoals == scoreOfMatch.AwayGoals &&
                         match.HomeGoalsPredicted == match.AwayGoalsPredicted))
                    {
                        successResultPredictions++;
                    }

                    if (scoreOfMatch.HomeGoals == match.HomeGoalsPredicted &&
                        scoreOfMatch.AwayGoals == match.AwayGoalsPredicted)
                    {
                        successScorePredictions++;
                    }

                    allMatches++;
                }
            }
            return(Tuple.Create(allMatches, successResultPredictions, successScorePredictions));
        }
Exemplo n.º 6
0
        private async Task <bool> RenameEpisodesUI()
        {
            using var renamer = new EpisodeRenameForm();
            var folder   = tvwFolder.SelectedNode.Tag.ToString();
            var episodes = await SeasonHelper.GetEpisodes(_tvdb, folder);

            var seriesFolder = new DirectoryInfo(folder).Parent.FullName;
            var seriesName   = SeriesIOHelper.GetSeriesMetadata(seriesFolder).Series.Title;

            renamer.ShowDialog(seriesName, folder, episodes);
            LoadAllFiles(folder);
            return(renamer.GetSeasonData);
        }
Exemplo n.º 7
0
        public void CanFoundCorrectSeason()
        {
            DateTime currDate = new DateTime(2010, 1, 1);

            Assert.IsTrue(Season.Winter == SeasonHelper.GetCurrentSeason(currDate));

            currDate = new DateTime(2010, 4, 1);
            Assert.IsTrue(Season.Spring == SeasonHelper.GetCurrentSeason(currDate));

            currDate = new DateTime(2010, 9, 21);
            Assert.IsTrue(Season.Fall == SeasonHelper.GetCurrentSeason(currDate));

            currDate = new DateTime(2010, 8, 24);
            Assert.IsTrue(Season.Summer == SeasonHelper.GetCurrentSeason(currDate));
        }
 public ActionResult NextRound()
 {
     using (var ctx = new FootballEntities())
     {
         var data         = new List <MainPageModel>();
         var actualSeason = SeasonHelper.GetCurrentSeason(DateTime.Today);
         var actualRound  = MatchweekHelper.GetCurrentMatchweek();
         //tu dodac jeszcze obrazek na koniec sezonu
         foreach (var x in ctx.Matches.Where(d => (d.Matchweek == actualRound) && d.Season.Equals(actualSeason))) // to zmienic żeby na koniec sezonu wyswietlalo obrazek
         {
             data.Add(new MainPageModel(x.Team1.FullName, x.Team.FullName, x.HomeGoalsPredicted, x.AwayGoalsPredicted, null, null, x.Date.Date));
         }
         ViewBag.round = actualRound;
         return(View(data));
     }
 }
 public ActionResult Table()
 {
     using (var ctx = new FootballEntities())
     {
         var actualSeason = SeasonHelper.GetCurrentSeason(DateTime.UtcNow);
         var teams        = new List <TeamModel>();
         var position     = 1;
         foreach (var singleTeam in ctx.FullStatistics.Where(e => e.Season == actualSeason).OrderByDescending(e => e.Points))
         {
             var name = singleTeam.Team.FullName;
             var team = new TeamModel(name, position++, singleTeam.MatchesPlayed, singleTeam.Points, singleTeam.MatchesWon,
                                      singleTeam.MatchesDrawn, singleTeam.MatchesLost, singleTeam.GoalsScored, singleTeam.GoalsLost,
                                      singleTeam.GoalsScored - singleTeam.GoalsLost, null);
             teams.Add(team);
         }
         return(View(teams));
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// This method replaced the original CheckPlantGrowthStage
        /// This method is public to avoid Protected memory access to the arguments (needs to be same access level as original)
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="facade"></param>
        public void CheckPlantGrowthStage(Entity entity, EntityUniverseFacade facade)
        {
            PlayerEntityLogic playerEntityLogic = entity.PlayerEntityLogic;
            Tile tile = default(Tile);
            PlantConfiguration config   = default(PlantConfiguration);
            Vector3I           cursor   = default(Vector3I);
            Vector3I           adjacent = default(Vector3I);
            Vector3I           core     = default(Vector3I);

            if (playerEntityLogic != null && playerEntityLogic.LookingAtTile(out cursor, out adjacent) && ((ItemFacade)facade).FindReadCompoundTileCore(cursor, TileAccessFlags.None, out core, out tile) && GameContext.PlantDatabase.TryGetByTile(tile, out config))
            {
                Season season            = SeasonHelper.FromInt(facade.DayNightCycle().GetSeason());
                bool   livesInThisSeason = config.LivesInSeason(season);

                Totem        totem;
                List <Totem> totems;
                bool         plantedInGreenhouse = (PlantLogic.GetValidTotemsOfType(PlantLogic.GreenhouseTotemCode, out totems) && PlantLogic.IsInTotemsRegion(totems, cursor, out totem));

                Notification notif;
                if (config.IsWitheredTile(tile))
                {
                    notif = ((!livesInThisSeason && !plantedInGreenhouse) ? GameContext.NotificationDatabase.CreateNotificationFromCode("staxel.notifications.checkPlantGrowth.witheredSeason", entity.Step, NotificationParams.CreateFromTranslation(season.GetCode()), false) : GameContext.NotificationDatabase.CreateNotificationFromCode("staxel.notifications.checkPlantGrowth.withered", entity.Step, NotificationParams.EmptyParams, false));
                }
                else if (config.IsWiltedTile(tile))
                {
                    notif = GameContext.NotificationDatabase.CreateNotificationFromCode("staxel.notifications.checkPlantGrowth.wilted", entity.Step, NotificationParams.EmptyParams, false);
                }
                else if (!livesInThisSeason && !plantedInGreenhouse)
                {
                    notif = GameContext.NotificationDatabase.CreateNotificationFromCode("staxel.notifications.checkPlantGrowth.season", entity.Step, NotificationParams.CreateFromTranslation(season.GetCode()), false);
                }
                else
                {
                    float  percentage  = config.GetGrowthPercentage(tile, config);
                    string description = (!(percentage < 0.1f)) ? ((!(percentage < 1f)) ? "hintText.checkPlantGrowth.fruited" : "hintText.checkPlantGrowth.growing") : "hintText.checkPlantGrowth.seed";
                    notif = GameContext.NotificationDatabase.CreateNotificationFromCode("staxel.notifications.checkPlantGrowth", entity.Step, NotificationParams.CreateFromTranslation(description), false);
                }
                playerEntityLogic.ShowNotification(notif);
            }
            entity.Logic.ActionFacade.NoNextAction();
        }
Exemplo n.º 11
0
        private void SetEffectiveness()
        {
            try
            {
                // Current Effectiveness = effectiveness of completed matchweek
                int    currentMatchweek     = MatchweekHelper.GetCurrentMatchweek() - 1;
                double currentEffectiveness = new ScoreEffectivenessService().Compute(currentMatchweek, SeasonHelper.GetCurrentSeason(DateTime.Now)) * 100;

                double previouslyEffectiveness = currentEffectiveness;
                if (currentMatchweek > 1)
                {
                    previouslyEffectiveness = new ScoreEffectivenessService().Compute(currentMatchweek - 1, SeasonHelper.GetCurrentSeason(DateTime.Now)) * 100;
                }

                string compareEffectiveness = "";
                double difference           = currentEffectiveness - previouslyEffectiveness;
                if (difference > 0)
                {
                    compareEffectiveness             = "+";
                    CompareEfficiencyLabel.ForeColor = System.Drawing.Color.Green;
                }
                else if (difference < 0)
                {
                    CompareEfficiencyLabel.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    CompareEfficiencyLabel.ForeColor = System.Drawing.Color.Black;
                }
                compareEffectiveness += difference.ToString();

                CurrentEfficiencyLabel.Text     = currentEffectiveness.ToString() + "%";
                CompareEfficiencyLabel.Location = new Point(CurrentEfficiencyLabel.Location.X + CurrentEfficiencyLabel.Width + 1, CurrentEfficiencyLabel.Location.Y);
                CompareEfficiencyLabel.Text     = compareEffectiveness + "%";

                Log("Skuteczność systemu została zaktualizowana.");
            }
            catch (Exception)
            {  }
        }
Exemplo n.º 12
0
 public void GenerateMatch(int seasonId)
 {
     using (var dc = ThaitaeDataDataContext.Create())
     {
         var isChampionLeagueFinal = dc.Leagues.Any(item => item.LeagueId == Convert.ToInt32(Session["leagueid"]) && (item.LeagueType == 1 || item.LeagueType == 2));
         if (!isChampionLeagueFinal)
         {
             var teamSeasonList =
                 dc.TeamSeasons.Join(dc.Teams, teamSeason => teamSeason.TeamId, team => team.TeamId,
                                     (teamSeason, team) => new { teamSeason.SeasonId, team.TeamId })
                 .Where(teamSeason => teamSeason.SeasonId == seasonId)
                 .ToList();
             for (var i = 0; i < teamSeasonList.Count; i++)
             {
                 for (var j = 0; j < teamSeasonList.Count; j++)
                 {
                     if (teamSeasonList[i].TeamId != teamSeasonList[j].TeamId)
                     {
                         Match match      = null;
                         var   matchExist = dc.Matches.Count(
                             item =>
                             item.SeasonId == seasonId && item.TeamHomeId == teamSeasonList[i].TeamId &&
                             item.TeamAwayId == teamSeasonList[j].TeamId);
                         if (matchExist == 0)
                         {
                             match = new Match
                             {
                                 SeasonId   = seasonId,
                                 MatchDate  = DateTime.Now,
                                 TeamHomeId = teamSeasonList[i].TeamId,
                                 TeamAwayId = teamSeasonList[j].TeamId
                             };
                             dc.Matches.InsertOnSubmit(match);
                             dc.SubmitChanges();
                         }
                         else
                         {
                             match = dc.Matches.Single(
                                 item =>
                                 item.SeasonId == seasonId && item.TeamHomeId == teamSeasonList[i].TeamId &&
                                 item.TeamAwayId == teamSeasonList[j].TeamId);
                         }
                         var teamHomeExist =
                             dc.TeamMatches.Count(
                                 item => item.MatchId == match.MatchId && item.TeamId == match.TeamHomeId);
                         if (teamHomeExist == 0)
                         {
                             var teamHomeMatch = new TeamMatch
                             {
                                 MatchId  = match.MatchId,
                                 TeamId   = match.TeamHomeId,
                                 TeamHome = 1,
                                 SeasonId = match.SeasonId
                             };
                             dc.TeamMatches.InsertOnSubmit(teamHomeMatch);
                             dc.SubmitChanges();
                         }
                         var teamAwayExist =
                             dc.TeamMatches.Count(
                                 item => item.MatchId == match.MatchId && item.TeamId == match.TeamAwayId);
                         if (teamAwayExist == 0)
                         {
                             var teamAwayMatch = new TeamMatch
                             {
                                 MatchId  = match.MatchId,
                                 TeamId   = match.TeamAwayId,
                                 TeamHome = 0,
                                 SeasonId = match.SeasonId
                             };
                             dc.TeamMatches.InsertOnSubmit(teamAwayMatch);
                             dc.SubmitChanges();
                         }
                     }
                 }
             }
         }
         else
         {
             var isFinished = SeasonHelper.CheckGroupSeasonIsFinnish(seasonId);
         }
     }
 }
Exemplo n.º 13
0
        public static void Main(string[] args)
        {
            string _filepath = "";

            var date = ExecutionDateHelper.GetLastExecutionDate();

            try
            {
                Console.WriteLine("\nDownloading csv stared...");
                var csv = new CsvDownloader();
                _filepath = csv.GetScoresCsv(DateTime.Now);
                logger.Info("Csv file has been saved as: " + _filepath);
                Console.WriteLine("Downloading csv succeeded. File is located in: {0}", _filepath);
            }
            catch (Exception e)
            {
                logger.Error("Error while downloading csv file", e);
                Console.WriteLine("Downloading csv file failed.");
                return;
            }

            try
            {
                Console.WriteLine("\nParsing csv started...");
                var cs = new CsvService();
                var n  = cs.InsertScores(_filepath, date);
                logger.Info(n + " score records have been added to database");
                Console.WriteLine("Inserting scores to database succeeded.\n{0} records have been added", n);
                if (n > 0)
                {
                    ExecutionDateHelper.SetExecutionDate();
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while inserting scores.", e);
                Console.WriteLine("Inserting scores to database failed.");
                return;
            }

            try
            {
                Console.WriteLine("\nPredicting scores started...");
                var    p         = new Predictor();
                string season    = SeasonHelper.GetCurrentSeason(DateTime.Now);
                int    matchweek = MatchweekHelper.GetCurrentMatchweek();

                if (matchweek == 0 || matchweek == 38)
                {
                    season    = SeasonHelper.GetNextSeason(season);
                    matchweek = 1;
                }

                logger.InfoFormat("Prediction will be run for matchweek {0} of season {1}", matchweek, season);
                List <Match> sc = p.Predict(season, matchweek);
                logger.Info("Prediction finished successfully");
                Console.WriteLine("Predicting process succeeded.");
                Console.WriteLine("Predicted scores are:\n");
                foreach (var s in sc)
                {
                    Console.WriteLine("{0} - {1}\t\t{2}:{3}", s.Team1.Name, s.Team.Name, s.HomeGoalsPredicted, s.AwayGoalsPredicted);
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while predicting.", e);
                Console.WriteLine("\nAn error occured while predicting scores.");
                return;
            }

            logger.Info("Bye");
            Console.WriteLine("\nProgram finished.");
        }
Exemplo n.º 14
0
        /// <summary>
        /// DailyVisit before function
        /// </summary>
        /// <param name="plantBlob"></param>
        /// <param name="plantLocation"></param>
        /// <param name="plantTile"></param>
        /// <param name="soilLocation"></param>
        /// <param name="soilTile"></param>
        /// <param name="universe"></param>
        /// <param name="weatherWatered"></param>
        /// <returns></returns>
        public bool DailyVisit(Blob plantBlob, Vector3I plantLocation, Tile plantTile, Vector3I soilLocation, Tile soilTile, EntityUniverseFacade universe, bool weatherWatered)
        {
            // Return true in case it concerns a greenhouse plant

            int  day     = universe.DayNightCycle().Day;
            int  season  = universe.DayNightCycle().GetSeason();
            bool watered = GameContext.FarmingDatabase.IsWateredMaterial(soilTile.Configuration);

            if (GameContext.PlantDatabase.IsGrowable(plantTile))
            {
                PlantConfiguration  plantConfiguration = GameContext.PlantDatabase.GetByTile(plantTile.Configuration);
                DeterministicRandom rnd       = GameContext.RandomSource;
                bool         requiresWatering = GameContext.PlantDatabase.RequiresWatering(plantTile);
                long         lastChangedDay   = plantBlob.GetLong("day", -1L);
                int          prevSeason2      = (int)plantBlob.GetLong("season", -1L);
                List <Totem> totems;
                Totem        totem;
                bool         plantedInGreenhouse = (PlantLogic.GetValidTotemsOfType(PlantLogic.GreenhouseTotemCode, out totems) && PlantLogic.IsInTotemsRegion(totems, plantLocation, out totem));

                if (plantConfiguration.LivesInSeason(SeasonHelper.FromInt(season)) ||
                    !plantConfiguration.LivesInSeason(SeasonHelper.FromInt(season)) && !plantedInGreenhouse)
                {
                    return(true);
                }

                Logger.WriteLine("Custom plant DailyVisit");

                if (prevSeason2 == -1)
                {
                    prevSeason2 = season;
                }

                if (lastChangedDay == -1 || lastChangedDay > day)
                {
                    lastChangedDay = day - 1;
                    PlantLogic.FarmDatabaseTileUpdated.Invoke(GameContext.FarmingDatabase, new object[] { plantLocation, lastChangedDay, plantConfiguration.GatherableIsHarvestable, season });
                }

                Vector2I window2 = default(Vector2I);
                Vector2I window3 = default(Vector2I);
                Logger.WriteLine("Plant: " + plantConfiguration.Code);
                Logger.WriteLine("Watered: " + watered.ToString() + " | RequiresWatering: " + requiresWatering.ToString() + " | CanWilt: " + plantConfiguration.CanWilt(plantTile, out window2).ToString() + " | CanWither: " + plantConfiguration.CanWither(plantTile, out window3).ToString());

                long totalDays  = day - lastChangedDay;
                int  growthDays = 0;
                int  daysPassed = 1;
                for (int i = 0; i < totalDays; i++)
                {
                    Vector2I window = default(Vector2I);
                    if (!watered && requiresWatering && plantConfiguration.CanWilt(plantTile, out window))
                    {
                        Logger.WriteLine("Wilting result:" + ((bool)PlantLogic.FarmDatabaseChangeTile.Invoke(GameContext.FarmingDatabase, new object[] { plantLocation, plantConfiguration.MakeWiltedTile(plantTile), universe, plantConfiguration.GatherableIsHarvestable, null, TileAccessFlags.IgnoreEntities })).ToString());
                        int transitionPeriod3 = rnd.Next(window.X, window.Y);
                        if (transitionPeriod3 <= daysPassed - growthDays &&
                            (bool)PlantLogic.FarmDatabaseChangeTile.Invoke(GameContext.FarmingDatabase, new object[] { plantLocation, plantConfiguration.MakeWiltedTile(plantTile), universe, plantConfiguration.GatherableIsHarvestable, null, TileAccessFlags.IgnoreEntities }))
                        {
                            Logger.WriteLine("Wilting greenhouse plant");
                            break;
                        }
                    }
                    if (!watered && requiresWatering && plantConfiguration.CanWither(plantTile, out window))
                    {
                        Logger.WriteLine("Withering result: " + ((bool)PlantLogic.FarmDatabaseChangeTile.Invoke(GameContext.FarmingDatabase, new object[] { plantLocation, plantConfiguration.MakeWitheredTile(plantTile), universe, plantConfiguration.GatherableIsHarvestable, null, TileAccessFlags.IgnoreEntities })).ToString());
                        int transitionPeriod2 = rnd.Next(window.X, window.Y);
                        if (transitionPeriod2 <= daysPassed - growthDays &&
                            (bool)PlantLogic.FarmDatabaseChangeTile.Invoke(GameContext.FarmingDatabase, new object[] { plantLocation, plantConfiguration.MakeWitheredTile(plantTile), universe, plantConfiguration.GatherableIsHarvestable, null, TileAccessFlags.IgnoreEntities }))
                        {
                            Logger.WriteLine("Withering greenhouse plant");
                            break;
                        }
                    }
                    if (!watered && requiresWatering && !plantConfiguration.CanWilt(plantTile, out window) && !plantConfiguration.CanWither(plantTile, out window))
                    {
                        Logger.WriteLine("Set as harvestable");
                        PlantLogic.FarmDatabaseTileUpdated.Invoke(GameContext.FarmingDatabase, new object[] { plantLocation, day, plantConfiguration.GatherableIsHarvestable, season });
                        break;
                    }
                    if ((watered || !requiresWatering || (plantConfiguration.GatherableIsHarvestable && rnd.NextBool())) && plantConfiguration.CanGrow(plantTile, SeasonHelper.FromInt(season), out window))
                    {
                        int transitionPeriod = rnd.Next(window.X, window.Y);
                        if (transitionPeriod <= daysPassed - growthDays &&
                            (bool)PlantLogic.FarmDatabaseChangeTile.Invoke(GameContext.FarmingDatabase, new object[] { plantLocation, plantConfiguration.MakeGrowTile(plantTile, rnd), universe, plantConfiguration.GatherableIsHarvestable, null, TileAccessFlags.IgnoreEntities }))
                        {
                            growthDays += transitionPeriod;
                            if (!universe.ReadTile(plantLocation, TileAccessFlags.None, out plantTile))
                            {
                                return(true);
                            }
                        }
                    }

                    daysPassed++;
                }


                if (!weatherWatered && watered)
                {
                    Tile unwateredTile = (Tile)PlantLogic.FarmDatabaseMakeUnwateredMaterial.Invoke(GameContext.FarmingDatabase, new object[] { soilTile });
                    PlantLogic.FarmDatabaseChangeTile.Invoke(null, new object[] { soilLocation, unwateredTile, universe, false, null, TileAccessFlags.IgnoreEntities });
                }

                Tile tempPlant            = default(Tile);
                PlantConfiguration config = default(PlantConfiguration);
                bool isMaterialWaterable  = (bool)PlantLogic.FarmDatabaseIsMaterialWaterable.Invoke(GameContext.FarmingDatabase, new object[] { soilTile.Configuration });
                if (weatherWatered && !watered && isMaterialWaterable && universe.ReadTile(plantLocation, TileAccessFlags.None, out tempPlant) && GameContext.PlantDatabase.TryGetByTile(tempPlant, out config))
                {
                    Tile wateredTile = (Tile)PlantLogic.FarmDatabaseMakeWateredMaterial.Invoke(GameContext.FarmingDatabase, new object[] { soilTile });
                    PlantLogic.FarmDatabaseChangeTile.Invoke(null, new object[] { soilLocation, wateredTile, universe, false, null, TileAccessFlags.IgnoreEntities });
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 15
0
        protected void GenTeam_Click(object sender, EventArgs e)
        {
            if (Session["seasonid"] == null)
            {
                return;
            }
            if (Convert.ToInt32(Session["seasonid"]) == 0)
            {
                return;
            }
            var seasonList = SeasonHelper.GetChampionLeagueGroupSeasonList(SeasonHelper.CheckIsEuropaSeasonId(Convert.ToInt32(Session["seasonid"])));

            foreach (var season in seasonList)
            {
                var isFinished = SeasonHelper.CheckGroupSeasonIsFinnish(season.SeasonId);
                if (!isFinished)
                {
                    JavaScriptHelper.Alert("ยังใส่ผล Champion League ไม่ครบทุก Group");
                    return;
                }
            }

            using (var dc = ThaitaeDataDataContext.Create())
            {
                var checkRecord = dc.TeamSeasons.Any(item => item.SeasonId == Convert.ToInt32(Session["seasonid"]));
                if (checkRecord)
                {
                    JavaScriptHelper.Alert("ต้องลบทีมออกให้หมดก่อนถึงจะกดปุ่มนี้ได้"); return;
                }
            }
            foreach (var season in seasonList)
            {
                List <TeamSeason> teamSeasonList;
                var leagueId = Convert.ToInt32(Session["leagueid"]);
                int i;
                if (leagueId == 14)
                {
                    teamSeasonList = TeamSeasonHelper.GetChampionsLeagueFinalTeamList(season.SeasonId);
                    i = 1;
                }
                else
                {
                    teamSeasonList = TeamSeasonHelper.GetEuropaLeagueFinalTeamList(season.SeasonId);
                    i = 2;
                }

                foreach (var teamSeason in teamSeasonList)
                {
                    using (var dc = ThaitaeDataDataContext.Create())
                    {
                        var teamFinalSelected =
                            TeamSeasonHelper.GetChampionsLeagueFinalTeamFromGroupSeasonId(teamSeason.SeasonId,
                                                                                          teamSeason.TeamId);
                        if (teamFinalSelected == null)
                        {
                            var teamFinal = new TeamSeason
                            {
                                TeamDrew         = 0,
                                TeamGoalAgainst  = 0,
                                TeamGoalDiff     = 0,
                                TeamGoalFor      = 0,
                                TeamLoss         = 0,
                                TeamMatchPlayed  = 0,
                                TeamPts          = 0,
                                TeamRedCard      = 0,
                                TeamWon          = 0,
                                TeamYellowCard   = 0,
                                GroupSeasonId    = 0,
                                GroupSeasonOrder = leagueId == 14 ? i++ : i--,
                                TeamId           = teamSeason.TeamId,
                                SeasonId         = Convert.ToInt32(Session["seasonid"])
                            };
                            dc.TeamSeasons.InsertOnSubmit(teamFinal);
                        }
                        else
                        {
                            teamFinalSelected.GroupSeasonOrder = leagueId == 14 ? i++ : i--;
                        }

                        dc.SubmitChanges();
                    }
                }
            }
        }
Exemplo n.º 16
0
        public ActionResult H2H(TeamsInfoModel model)
        {
            using (var ctx = new FootballEntities())
            {
                var teams = ctx.Teams.Select(x => x.FullName).ToList();
                ViewBag.Teams      = teams;
                ViewBag.allSeasons = GetListOfAvailablesSeasons(ctx);
                if (model.Team1 == null || model.Team2 == null || model.Team1.Equals(model.Team2))
                {
                    return(View());
                }

                var team1Id = ctx.Teams.FirstOrDefault(e => e.FullName.Equals(model.Team1)).Id;
                var team2Id = ctx.Teams.FirstOrDefault(e => e.FullName.Equals(model.Team2)).Id;

                var singleMatchStats  = new List <MatchStatisticsModel>();
                var today             = DateTime.UtcNow.Date;
                var actualSeason      = SeasonHelper.GetCurrentSeason(today);
                var seasonTwoYearsAgo = SeasonHelper.GetCurrentSeason(DateTime.Today.AddYears(-2));
                if (model.SeasonTo == null)
                {
                    model.SeasonTo = actualSeason;
                }
                if (model.SeasonSince == null)
                {
                    model.SeasonSince = seasonTwoYearsAgo;
                }

                var iFrom = Int32.Parse(model.SeasonSince.Remove(4));
                var iTo   = Int32.Parse(model.SeasonTo.Remove(4));
                if (iFrom > iTo)
                {
                    var tmp = model.SeasonSince;
                    model.SeasonSince = model.SeasonTo;
                    model.SeasonTo    = tmp;
                }

                foreach (var match in ctx.Matches.Where(e => ((e.HomeId == team1Id && e.AwayId == team2Id) ||
                                                              e.HomeId == team2Id && e.AwayId == team1Id) &&
                                                        DateTime.Compare(e.Date, today) < 0)
                         .OrderByDescending(d => d.Date))
                {
                    if (!SeasonsComapare(model.SeasonSince, model.SeasonTo, match.Season))
                    {
                        continue;
                    }
                    var homeTeam = ctx.Teams.First(q => q.Id == match.HomeId).FullName;
                    var awayTeam = ctx.Teams.First(q => q.Id == match.AwayId).FullName;
                    var stats    = ctx.Scores.FirstOrDefault(q => q.MatchId == match.Id);
                    if (stats == null)
                    {
                        continue;
                    }
                    var season = SeasonHelper.GetCurrentSeason(match.Date);
                    singleMatchStats.Add(new MatchStatisticsModel(homeTeam, awayTeam, match.Date,
                                                                  match.HomeGoalsPredicted, match.AwayGoalsPredicted, match.Matchweek, stats.HomeGoals,
                                                                  stats.AwayGoals,
                                                                  stats.HomeShots, stats.AwayShots, stats.HomeShotsOnTarget, stats.AwayShotsOnTarget,
                                                                  stats.HomeCorners,
                                                                  stats.AwayCorners, stats.HomeFouls, stats.AwayFouls, stats.HomeYellowCards,
                                                                  stats.AwayYellowCards,
                                                                  stats.HomeRedCards, stats.AwayRedCards, stats.HalfTimeHomeGoals, stats.HalfTimeAwayGoals,
                                                                  stats.Referee, season));
                }

                ViewBag.Matches = singleMatchStats;
                return(View());
            }
        }
Exemplo n.º 17
0
        public ActionResult TeamStatistics(TeamsInfoModel model)
        {
            if (model.Team1 == null)
            {
                model.Team1 = "";
            }
            using (var ctx = new FootballEntities())
            {
                var seasonStatsOfTeam = new List <TeamModel>();
                var teams             = ctx.Teams.Select(x => x.FullName).ToList();
                ViewBag.teams      = teams;
                ViewBag.allSeasons = GetListOfAvailablesSeasons(ctx);
                if (model.Team1.Equals(""))
                {
                    return(View());
                }

                var today             = DateTime.UtcNow.Date;
                var season            = SeasonHelper.GetCurrentSeason(today);
                var seasonTwoYearsAgo = SeasonHelper.GetCurrentSeason(DateTime.Today.AddYears(-2));
                if (model.SeasonTo == null)
                {
                    model.SeasonTo = season;
                }
                if (model.SeasonSince == null)
                {
                    model.SeasonSince = seasonTwoYearsAgo;
                }

                var iFrom = Int32.Parse(model.SeasonSince.Remove(4));
                var iTo   = Int32.Parse(model.SeasonTo.Remove(4));
                if (iFrom > iTo)
                {
                    var tmp = model.SeasonSince;
                    model.SeasonSince = model.SeasonTo;
                    model.SeasonTo    = tmp;
                }
                var statsOfPrediction = GetSuccessRateOfPrediction(model);
                ViewBag.matchesPredicted      = statsOfPrediction.Item1;
                ViewBag.rightResultPrediction = statsOfPrediction.Item2;
                ViewBag.rightScoresPrediction = statsOfPrediction.Item3;


                var teamId = ctx.Teams.FirstOrDefault(e => e.FullName.Equals(model.Team1)).Id;
                //dodac liczenia miejsca w tabeli
                foreach (var singleTeam in ctx.FullStatistics.Where(e => e.TeamId == teamId).OrderByDescending(d => d.Season))
                {
                    if (!SeasonsComapare(model.SeasonSince, model.SeasonTo, singleTeam.Season))
                    {
                        continue;
                    }
                    var name = singleTeam.Team.FullName;
                    var team = new TeamModel(name, 0, singleTeam.MatchesPlayed, singleTeam.Points,
                                             singleTeam.MatchesWon,
                                             singleTeam.MatchesDrawn, singleTeam.MatchesLost, singleTeam.GoalsScored,
                                             singleTeam.GoalsLost,
                                             singleTeam.GoalsScored - singleTeam.GoalsLost, singleTeam.Season);
                    seasonStatsOfTeam.Add(team);
                }
                ViewBag.SeasonStats = seasonStatsOfTeam;


                var singleMatchStats = new List <MatchStatisticsModel>();
                var actualRound      = MatchweekHelper.GetCurrentMatchweek();

                foreach (var match in ctx.Matches.Where(e => (e.HomeId == teamId || e.AwayId == teamId) &&
                                                        DateTime.Compare(e.Date, today) < 0).OrderByDescending(d => d.Date))
                {
                    if (!SeasonsComapare(model.SeasonSince, model.SeasonTo, match.Season))
                    {
                        continue;
                    }
                    var homeTeam      = ctx.Teams.First(q => q.Id == match.HomeId).FullName;
                    var awayTeam      = ctx.Teams.First(q => q.Id == match.AwayId).FullName;
                    var seasonOfMatch = SeasonHelper.GetCurrentSeason(match.Date);
                    var stats         = ctx.Scores.FirstOrDefault(q => q.MatchId == match.Id);

                    if (stats == null)
                    {
                        continue;
                    }

                    singleMatchStats.Add(new MatchStatisticsModel(homeTeam, awayTeam, match.Date,
                                                                  match.AwayGoalsPredicted, match.HomeGoalsPredicted, match.Matchweek, stats.HomeGoals, stats.AwayGoals,
                                                                  stats.HomeShots, stats.AwayShots, stats.HomeShotsOnTarget, stats.AwayShotsOnTarget, stats.HomeCorners,
                                                                  stats.AwayCorners, stats.HomeFouls, stats.AwayFouls, stats.HomeYellowCards, stats.AwayYellowCards,
                                                                  stats.HomeRedCards, stats.AwayRedCards, stats.HalfTimeHomeGoals, stats.HalfTimeAwayGoals,
                                                                  stats.Referee, seasonOfMatch));
                }

                ViewBag.Matches = singleMatchStats;

                //url
                var url = ctx.Teams.FirstOrDefault(x => x.FullName.Equals(model.Team1)).ImageURL;
                ViewBag.url = url;

                return(View());
            }
        }