private static int CheckCurrentRound(this TournamnetModel model)
        {
            int output = 1; //check round one

            foreach (List <MatchupModel> round in model.Rounds)
            {
                //check if all the matchups have a winner (if every single matchup has a winner
                //Its mean that the round is complete)
                if (round.All(x => x.Winner != null))
                {
                    output += 1; //check the next round
                }
                else
                {
                    return(output); //we move return here so we can know that the tournament is complete
                }
            }

            //return output; //this will return the round number that doesn't has a winner (all the rounds after
            // this round will not have winners, because its depend on this round)
            //so this round is the current round.
            //Tournament is complete
            CompleteTournament(model);

            return(output - 1);
        }
        public static List <TournamnetModel> ConvertToTournamentModels(
            this List <string> lines)
        {
            // id = 0
            // Tournament = 1
            // EntryFee = 2
            // EnteredTeams = 3
            // Prizes = 4
            // Rounds = 5
            //the text file should look like the following
            //id,TournamentName,EntryFee,(id|id|id - Entered Teams),(id|id|id - Prizes),(Rounds - id^id^id|id^id^id|id^id^id)
            List <TournamnetModel> output   = new List <TournamnetModel>();
            List <TeamModel>       teams    = GlobalConfig.TeamFile.FullFilePath().LoadFile().ConvertToTeamModels();
            List <PrizeModel>      prizes   = GlobalConfig.PrizesFile.FullFilePath().LoadFile().ConvertToPrizeModels();
            List <MatchupModel>    matchups = GlobalConfig.MatchupFile
                                              .FullFilePath()
                                              .LoadFile()
                                              .ConvertToMatchupModels();

            foreach (string line in lines)
            {
                string[] cols = line.Split(',');

                TournamnetModel tm = new TournamnetModel();
                tm.Id             = int.Parse(cols[0]);
                tm.TournamentName = cols[1];
                tm.EntryFee       = decimal.Parse(cols[2]);

                string[] teamIds = cols[3].Split('|');
                foreach (string id in teamIds)
                {
                    tm.EnteredTeams.Add(teams.Where(x => x.Id == int.Parse(id)).First());
                }

                if (cols[4].Length > 0)
                {
                    string[] prizeIds = cols[4].Split('|');
                    foreach (string id in prizeIds)
                    {
                        tm.Prizes.Add(prizes.Where(x => x.Id == int.Parse(id)).First());
                    }
                }

                // Capture Rounds information
                string[] rounds = cols[5].Split('|');

                foreach (string round in rounds)
                {
                    string[]            msText = round.Split('^');
                    List <MatchupModel> ms     = new List <MatchupModel>();
                    foreach (string matchupModelTextId in msText)
                    {
                        ms.Add(matchups.Where(x => x.Id == int.Parse(matchupModelTextId)).First());
                    }
                    tm.Rounds.Add(ms);
                }
                output.Add(tm);
            }
            return(output);
        }
        public static void UpdateTournamentResult(TournamnetModel model)
        {
            int startingRound = model.CheckCurrentRound();

            List <MatchupModel> toScore = new List <MatchupModel>();

            foreach (List <MatchupModel> round in model.Rounds)
            {
                foreach (MatchupModel rm in round)
                {
                    //check if (any of the entries has a score not 0, or entries =1 (thats means we have a bye team))
                    // and we don't have a winner
                    if (rm.Winner == null && (rm.Entries.Any(x => x.Score != 0) || rm.Entries.Count == 1))
                    {
                        toScore.Add(rm);
                    }
                }
            }

            MarkWinnerInMatchups(toScore);

            AdvanceWinners(toScore, model);


            toScore.ForEach(x => GlobalConfig.Connection.updateMatchup(x));
            int endingRound = model.CheckCurrentRound();

            if (endingRound > startingRound)
            {
                model.AlertUsersToNewRound();
            }
        }
Beispiel #4
0
        private void loadTournamentButton_Click(object sender, EventArgs e)
        {
            TournamnetModel      tm  = (TournamnetModel)loadExistingTournamentDropDown.SelectedItem;
            TournamentViewerForm frm = new TournamentViewerForm(tm);

            frm.Show();
        }
        private static void CreateOtherRounds(TournamnetModel model, int rounds)
        {
            int round = 2;
            List <MatchupModel> previousRound = model.Rounds[0];
            List <MatchupModel> currRound     = new List <MatchupModel>();
            MatchupModel        currMatchup   = new MatchupModel();

            while (round <= rounds)
            {
                foreach (MatchupModel match in previousRound)
                {
                    currMatchup.Entries.Add(new MatchupEntryModel {
                        ParentMatchup = match
                    });
                    if (currMatchup.Entries.Count > 1)
                    {
                        currMatchup.MatchupRound = round;
                        currRound.Add(currMatchup);
                        currMatchup = new MatchupModel();
                    }
                }

                model.Rounds.Add(currRound);
                previousRound = currRound;
                currRound     = new List <MatchupModel>();
                round        += 1;
            }
        }
        //- Order our list randomly of teams
        //- Check if it is big enough - if not, add in byes (2 to the n power, 2^4 )
        //- Create our first round of matchups
        //- Create every round after that (divide by 2), for example (16 teams), 8 matchups -> 4 -> 2 -> 1
        public static void CreateRounds(TournamnetModel model)
        {
            List <TeamModel> randomizedTeams = RandomizeTeamOrder(model.EnteredTeams);
            int rounds = FindNumberOfRounds(randomizedTeams.Count);
            int byes   = NumberOfByes(rounds, randomizedTeams.Count);

            model.Rounds.Add(CreateFirstRound(byes, randomizedTeams));

            CreateOtherRounds(model, rounds);
        }
        public void CompleteTournament(TournamnetModel model)
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(
                       GlobalConfig.CnnString(db)))
            {
                var p = new DynamicParameters();
                p.Add("@id", model.Id);

                connection.Execute("dbo.spTournaments_Complete", p, commandType: CommandType.StoredProcedure);
            }
        }
        private void SaveTournamentEntries(IDbConnection connection, TournamnetModel model)
        {
            foreach (TeamModel tm in model.EnteredTeams)
            {
                var p = new DynamicParameters();
                p.Add("@TournamentId", model.Id);
                p.Add("@TeamId", tm.Id);
                p.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                connection.Execute("dbo.spTournamentEntries_Insert", p, commandType: CommandType.StoredProcedure);
            }
        }
        private void SaveTournamentPrizes(IDbConnection connection, TournamnetModel model)
        {
            foreach (PrizeModel pz in model.Prizes)
            {
                var p = new DynamicParameters();
                p.Add("@TournamentId", model.Id);
                p.Add("@PrizeId", pz.Id);
                p.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                connection.Execute("dbo.spTournamentPrizes_Insert", p, commandType: CommandType.StoredProcedure);
            }
        }
        private void SaveTournament(IDbConnection connection, TournamnetModel model)
        {
            var p = new DynamicParameters();

            p.Add("@TournamentName", model.TournamentName);
            p.Add("@EntryFee", model.EntryFee);
            p.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

            connection.Execute("dbo.spTournaments_Insert", p, commandType: CommandType.StoredProcedure);

            model.Id = p.Get <int>("@id");
        }
        private void SaveTournamentRounds(IDbConnection connection, TournamnetModel model)
        {
            //List<List<MatchupModel>> Rounds
            //List<MatchupentryModel> Entries

            // Loop through the rounds
            // Loop through the matchups
            // Save the matchup
            // Loop through the entries and save them

            foreach (List <MatchupModel> round in model.Rounds)
            {
                foreach (MatchupModel matchup in round)
                {
                    var p = new DynamicParameters();
                    p.Add("@TournamentId", model.Id);
                    p.Add("@MatchupRound", matchup.MatchupRound);
                    p.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                    connection.Execute("dbo.spMatchups_Insert", p, commandType: CommandType.StoredProcedure);

                    matchup.Id = p.Get <int>("@id");

                    foreach (MatchupEntryModel entry in matchup.Entries)
                    {
                        p = new DynamicParameters();
                        p.Add("@MatchupId", matchup.Id);

                        if (entry.ParentMatchup == null)
                        {
                            p.Add("@ParentMatchupId", null);
                        }
                        else
                        {
                            p.Add("@ParentMatchupId", entry.ParentMatchup.Id);
                        }
                        if (entry.Teamcompeting == null)
                        {
                            p.Add("@TeamCompetingId", null);
                        }
                        else
                        {
                            p.Add("@TeamCompetingId", entry.Teamcompeting.Id);
                        }
                        p.Add("@id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);

                        connection.Execute("dbo.spMatchupEntries_Insert", p, commandType: CommandType.StoredProcedure);
                    }
                }
            }
        }
        public void CompleteTournament(TournamnetModel model)
        {
            List <TournamnetModel> tournaments = GlobalConfig.TournamentFile
                                                 .FullFilePath()
                                                 .LoadFile()
                                                 .ConvertToTournamentModels();


            tournaments.Remove(model);

            tournaments.SaveToTournamentFile();

            TournamentLogic.UpdateTournamentResult(model);
        }
Beispiel #13
0
        public TournamentViewerForm(TournamnetModel tournamnetModel)
        {
            InitializeComponent();

            tournamnet = tournamnetModel;

            tournamnet.onTournamentComplete += Tournamnet_onTournamentComplete;

            WireUpLists();

            LoadFormData();

            LoadRounds();
        }
        public void CreateTournament(TournamnetModel model)
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(
                       GlobalConfig.CnnString(db)))
            {
                SaveTournament(connection, model);

                SaveTournamentPrizes(connection, model);

                SaveTournamentEntries(connection, model);

                SaveTournamentRounds(connection, model);

                TournamentLogic.UpdateTournamentResult(model);
            }
        }
        public static void AlertUsersToNewRound(this TournamnetModel model)
        {
            int currentRoundNumber           = model.CheckCurrentRound();
            List <MatchupModel> currentRound = model.Rounds.Where(x => x.First().MatchupRound == currentRoundNumber).First();

            foreach (MatchupModel matchup in currentRound)
            {
                foreach (MatchupEntryModel me in matchup.Entries)
                {
                    foreach (PersonModel p in me.Teamcompeting.TeamMembers)
                    {
                        AlertPersonToNewRound(p, me.Teamcompeting.TeamName,
                                              matchup.Entries.Where(x => x.Teamcompeting != me.Teamcompeting).FirstOrDefault());
                    }
                }
            }
        }
Beispiel #16
0
        private void createTournamentButton_Click(object sender, EventArgs e)
        {
            //Validate data
            decimal fee           = 0;
            bool    feeAcceptable = decimal.TryParse(entryFeeValue.Text, out fee);

            if (!feeAcceptable)
            {
                MessageBox.Show("You need to enter a valid Entry Fee.", "Invalid Fee",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // 1-Create our Tournament model
            TournamnetModel tm = new TournamnetModel();

            tm.TournamentName = tournamentNameValue.Text;
            tm.EntryFee       = fee;

            //foreach (PrizeModel prize in selectedPrizes)
            //{
            //    tm.Prizes.Add(prize);
            //}
            //instead of for loop
            tm.Prizes       = selectedPrizes;
            tm.EnteredTeams = selectedTeams;

            // 2-Create/wire up our matchups
            TournamentLogic.CreateRounds(tm);

            // 3-Create Tournament entry
            // 4-Create all the prizes entries
            // 5-Create all of team entries
            //the next line will do the previous three tasks
            GlobalConfig.Connection.CreateTournament(tm);

            tm.AlertUsersToNewRound();

            TournamentViewerForm frm = new TournamentViewerForm(tm);

            frm.Show();
            this.Close();
        }
        public static void SaveRoundsToFile(this TournamnetModel model)
        {
            // Loop through each Round
            // Loop through each Matchup
            // Get the id for the new matchup and save the record
            // Loop through each entry, get the id, and save it

            foreach (List <MatchupModel> round in model.Rounds)
            {
                foreach (MatchupModel matchup in round)
                {
                    // Load all of the matchups from file
                    // Get the top id and 1
                    // Store the id
                    // Save the matchup records
                    matchup.SaveMatchupToFile();
                }
            }
        }
 private static void AdvanceWinners(List <MatchupModel> models, TournamnetModel tournamnet)
 {
     foreach (MatchupModel m in models)
     {
         foreach (List <MatchupModel> round in tournamnet.Rounds)
         {
             foreach (MatchupModel rm in round)
             {
                 foreach (MatchupEntryModel me in rm.Entries)
                 {
                     if (me.ParentMatchup != null)
                     {
                         if (me.ParentMatchup.Id == m.Id)
                         {
                             me.Teamcompeting = m.Winner;
                             GlobalConfig.Connection.updateMatchup(rm);
                         }
                     }
                 }
             }
         }
     }
 }
        public void CreateTournament(TournamnetModel model)
        {
            List <TournamnetModel> tournaments = GlobalConfig.TournamentFile
                                                 .FullFilePath()
                                                 .LoadFile()
                                                 .ConvertToTournamentModels();

            int currentId = 1;

            if (tournaments.Count > 0)
            {
                currentId = tournaments.OrderByDescending(x => x.Id).First().Id + 1;
            }

            model.Id = currentId;

            model.SaveRoundsToFile();

            tournaments.Add(model);

            tournaments.SaveToTournamentFile();

            TournamentLogic.UpdateTournamentResult(model);
        }
        private static void CompleteTournament(TournamnetModel model)
        {
            GlobalConfig.Connection.CompleteTournament(model);
            TeamModel winners = model.Rounds.Last().First().Winner;  //Linq expression
            //know all the loser in the last round
            TeamModel runnerUp = model.Rounds.Last().First().Entries.Where(x => x.Teamcompeting != winners).First().Teamcompeting;

            //we will calculate the prize only for 1st place and 2nd place
            decimal winnerPrize   = 0;
            decimal runnerUpPrize = 0;

            if (model.Prizes.Count > 0)
            {
                decimal totalIncome = model.EnteredTeams.Count * model.EntryFee;

                PrizeModel firstPlacePrize  = model.Prizes.Where(x => x.PlaceNumber == 1).FirstOrDefault();
                PrizeModel secondPlacePrize = model.Prizes.Where(x => x.PlaceNumber == 2).FirstOrDefault();

                if (firstPlacePrize != null)
                {
                    winnerPrize = firstPlacePrize.CalculatePrizePayout(totalIncome);
                }
                if (secondPlacePrize != null)
                {
                    runnerUpPrize = secondPlacePrize.CalculatePrizePayout(totalIncome);
                }
            }

            //send emails to all tournament
            string        subject = "";
            StringBuilder body    = new StringBuilder();


            subject = $"In { model.TournamentName }, { winners.TeamName } has won!";

            body.AppendLine("<h1>We have a WINNER!</h1>");
            body.AppendLine("<p>Congratulations to our winner on a great tournament.</p>");
            body.AppendLine("<br />");

            if (winnerPrize > 0)
            {
                body.AppendLine($"<p>{ winners.TeamName } will receive ${ winnerPrize }</p>");
            }


            if (runnerUpPrize > 0)
            {
                body.AppendLine($"<p>{ runnerUp.TeamName } will receive ${ runnerUpPrize }</p>");
            }

            body.AppendLine("<p>Thanks for a great tournament everyone!</p>");
            body.AppendLine("~Tournament Tracker");

            List <string> bcc = new List <string>();

            foreach (TeamModel t in model.EnteredTeams)
            {
                foreach (PersonModel p in t.TeamMembers)
                {
                    if (p.EmailAddress.Length > 0)
                    {
                        bcc.Add(p.EmailAddress);
                    }
                }
            }

            EmailLogic.SendEmail(new List <string>(), bcc, subject, body.ToString());

            //Complete Tournament
            model.CompleteTournament();
        }