private void SetStandings(TournamentMain tourn)
        {
            objTournMain = new TournamentMain();
            objTournMain = tourn;
            Title       += objTournMain.Name;

            Utilities.CalculatePlayerScores(ref objTournMain);

            List <TournamentMainPlayer> lstPlayerStandings = new List <TournamentMainPlayer>();

            foreach (TournamentMainPlayer player in objTournMain.Players.OrderBy(obj => obj.Rank).ToList())
            {
                //Separating out as to not tempt fate and inadvertently change any data unintentionally
                TournamentMainPlayer tmpPlayer = new TournamentMainPlayer();
                tmpPlayer.Rank       = player.Rank;
                tmpPlayer.PlayerName = player.PlayerName;
                tmpPlayer.Score      = player.Score;
                tmpPlayer.MOV        = player.MOV;
                tmpPlayer.SOS        = player.SOS;

                if (!player.Active)
                {
                    tmpPlayer.PlayerName += " (D)";
                }

                lstPlayerStandings.Add(tmpPlayer);
            }

            tournamentStandingsListView.ItemsSource = lstPlayerStandings;
        }
Ejemplo n.º 2
0
        //Set the copy of the player
        public PlayerToTournamentMainPlayer_ViewModel(Player player, int intTournamentId, int intRow, TournamentMainPlayer tournamentPlayer = null)
        {
            TournamentMainPlayer = new TournamentMainPlayer();

            if (tournamentPlayer is null)
            {
                TournamentMainPlayer.TournmentId = intTournamentId;
                TournamentMainPlayer.PlayerId    = player.Id;
                TournamentMainPlayer.PlayerName  = player.Name;
                TournamentMainPlayer.Active      = player.Active;
            }
            else
            {
                TournamentMainPlayer = tournamentPlayer;
            }

            if (intRow % 2 == 0)
            {
                RowBackgroundColor = Color.LightGray;
            }
            else
            {
                RowBackgroundColor = Color.Transparent;
            }
        }
Ejemplo n.º 3
0
        //Set the copy of the player
        public PlayerToTournamentMainPlayer_ViewModel(Player player, int intTournamentId, TournamentMainPlayer tournamentPlayer = null)
        {
            TournamentMainPlayer = new TournamentMainPlayer();

            if (tournamentPlayer is null)
            {
                TournamentMainPlayer.TournamentId = intTournamentId;
                TournamentMainPlayer.PlayerId     = player.Id;
                TournamentMainPlayer.PlayerName   = player.Name;
                TournamentMainPlayer.Active       = player.Active;
            }
            else
            {
                TournamentMainPlayer = tournamentPlayer;
            }
        }
Ejemplo n.º 4
0
        //Opening / OnAppearing
        protected override void OnAppearing()
        {
            this.IsBusy             = true;
            this.BarBackgroundColor = Color.Default;
            this.BarTextColor       = Color.Default;

            base.OnAppearing();

            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                objTournMain          = new TournamentMain();
                objTournMain          = conn.GetWithChildren <TournamentMain>(intTournID, true);
                Title                 = objTournMain.Name;
                intDefaultRoundLength = objTournMain.RoundTimeLength;

                UpdatePlayerList(conn);

                //Get full list of players
                List <Player> lstPlayers = conn.Query <Player>("SELECT * FROM Player WHERE (Active = 1 AND DateDeleted IS NULL) OR Id IN (" + objTournMain.ActivePlayersList() + ") ORDER BY Name");

                //Get list of currently active players in tournament
                string[] arrActivePlayers = objTournMain.ActivePlayersList().Split(',');


                //Set using the ViewModel version.  This allows being able to manipulate back and forth across the class properties, while displaying as intended on the GUI
                //while also ensuring none of the goings ons of the properties touching each other don't occur without this specific view model (such as the SQL table updates)
                lstViewPlayers = new ObservableCollection <PlayerToTournamentMainPlayer_ViewModel>();
                TournamentMainPlayer tmpTournamentMainPlayer = null;
                foreach (Player player in lstPlayers)
                {
                    player.Active = false;
                    if (arrActivePlayers.Contains <string>(player.Id.ToString()))
                    {
                        player.Active = true;
                    }

                    //Set the tournament player equivalent
                    tmpTournamentMainPlayer = null;
                    foreach (TournamentMainPlayer tournamentPlayer in objTournMain.Players)
                    {
                        if (tournamentPlayer.PlayerId == player.Id)
                        {
                            tmpTournamentMainPlayer = tournamentPlayer;
                            break;
                        }
                    }

                    lstViewPlayers.Add(new PlayerToTournamentMainPlayer_ViewModel(player, intTournID, tmpTournamentMainPlayer));
                }
                playersListView.ItemsSource = lstViewPlayers;
            }


            //Remove all the "Round" tabs and then repopulate them
            for (int index = this.Children.Count - 1; index > 0; index--)
            {
                if (index > 0)
                {
                    this.Children.RemoveAt(index);
                }
            }

            //Add each round as tabs
            foreach (TournamentMainRound round in objTournMain.Rounds)
            {
                Children.Add(new Tournaments_RoundInfo(this, "Rd " + round.Number, round.Id, objTournMain.Rounds.Count));

                //Help indicate that we're no longer in "Swiss" mode
                if (!round.Swiss)
                {
                    this.BarBackgroundColor = Color.LightGray;
                    this.BarTextColor       = Color.Black;
                }
            }

            //Try to shorten "players" if the tab count gets higher
            if (objTournMain.Rounds.Count > 4)
            {
                mainPlayerPage.Title = "Plyrs";
            }
            else
            {
                mainPlayerPage.Title = "Players";
            }

            //Select the last tab
            if (Children.Count > 0)
            {
                this.SelectedItem = Children[Children.Count - 1];
            }

            this.IsBusy = false;
        }
Ejemplo n.º 5
0
        private bool SetupSwissPlayers(ref List <TournamentMainPlayer> lstActiveTournamentPlayers, ref List <TournamentMainPlayer> lstActiveTournamentPlayers_Byes, int intAttempts = 0)
        {
            //Grab list of currently active players in the tournament
            Dictionary <int, List <TournamentMainPlayer> > dctActiveTournamentPlayerScores = new Dictionary <int, List <TournamentMainPlayer> >();

            foreach (TournamentMainPlayer player in objTournMain.Players)
            {
                if (player.Active)
                {
                    TournamentMainPlayer roundPlayer = new TournamentMainPlayer();
                    roundPlayer.PlayerId    = player.PlayerId;
                    roundPlayer.Score       = player.Score;
                    roundPlayer.OpponentIds = player.OpponentIds;

                    if (!player.Bye)
                    {
                        lstActiveTournamentPlayers.Add(roundPlayer);
                    }
                    else
                    {
                        lstActiveTournamentPlayers_Byes.Add(roundPlayer);
                        player.Bye = false;  //No longer has a Bye for the next round
                        player.ByeCount++;
                    }
                }
            }

            if (objTournMain.Rounds.Count == 0)
            {
                //First round, completely random player pairings
                lstActiveTournamentPlayers.Shuffle();
            }
            else
            {
                //Subsequent rounds, group up players with same win count as much as possible and randomize
                dctActiveTournamentPlayerScores = new Dictionary <int, List <TournamentMainPlayer> >();
                for (int i = objTournMain.Rounds.Count; i >= 0; i--)
                {
                    dctActiveTournamentPlayerScores.Add(i, new List <TournamentMainPlayer>());
                    foreach (TournamentMainPlayer activePlayer in lstActiveTournamentPlayers)
                    {
                        if (i == activePlayer.Score)
                        {
                            dctActiveTournamentPlayerScores[i].Add(activePlayer);
                        }
                    }

                    dctActiveTournamentPlayerScores[i].Shuffle(); //Shuffle all the players in each win bracket
                }

                //Clear out the active list, then go down the list and re-add them back in.
                lstActiveTournamentPlayers.Clear();
                for (int i = objTournMain.Rounds.Count; i >= 0; i--)
                {
                    if (dctActiveTournamentPlayerScores.ContainsKey(i))
                    {
                        foreach (TournamentMainPlayer activePlayer in dctActiveTournamentPlayerScores[i])
                        {
                            lstActiveTournamentPlayers.Add(activePlayer);
                        }
                    }
                }

                //If odd number of players, the last in the list will get a Bye
                //Get the lowest ranked player that hasn't had a bye already
                if (lstActiveTournamentPlayers.Count % 2 != 0)
                {
                    foreach (TournamentMainPlayer player in objTournMain.Players.OrderByDescending(obj => obj.Rank).ToList())
                    {
                        if (player.ByeCount == 0)
                        {
                            for (int i = lstActiveTournamentPlayers.Count - 1; i > 0; i--)
                            {
                                if (lstActiveTournamentPlayers[i].PlayerId == player.PlayerId)
                                {
                                    TournamentMainPlayer roundPlayer = lstActiveTournamentPlayers[i];
                                    lstActiveTournamentPlayers.RemoveAt(i);
                                    lstActiveTournamentPlayers.Add(roundPlayer);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }

                //Triple check to make sure no one is playing someone that they have already.
                //Reshuffle as necessary, multiple times (perhaps the tournament decides to keep going for whatever reason)
                if (intAttempts < 100)
                {
                    bool bFailMatchup = false;
                    int  intCount     = 1;
                    TournamentMainPlayer tmpPlayer1 = new TournamentMainPlayer();
                    foreach (TournamentMainPlayer player in lstActiveTournamentPlayers)
                    {
                        //Check every even player to see if they have already been paired up with the player before them (as they will be the ones paired up to went forwarded to the round table)
                        if (intCount % 2 == 0)
                        {
                            if (player.OpponentIds.Contains(tmpPlayer1.Id))
                            {
                                bFailMatchup = true;
                                break;
                            }
                        }
                        else
                        {
                            tmpPlayer1 = player;
                        }
                        intCount++;
                    }

                    if (bFailMatchup)
                    {
                        lstActiveTournamentPlayers      = new List <TournamentMainPlayer>();
                        lstActiveTournamentPlayers_Byes = new List <TournamentMainPlayer>();
                        SetupSwissPlayers(ref lstActiveTournamentPlayers, ref lstActiveTournamentPlayers_Byes, intAttempts++);
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 6
0
        public void GetAllTournamentInfo(SqlConnection sqlConn, ref List <TournamentMain> returnTournaments)
        {
            //Grab all the players associated with this tournament
            foreach (TournamentMain newTournament in returnTournaments)
            {
                using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsPlayers_GET", sqlConn))
                {
                    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@TournamentId", newTournament.Id);
                    using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
                    {
                        while (sqlReader.Read())
                        {
                            TournamentMainPlayer player = new TournamentMainPlayer
                            {
                                Id                 = sqlReader.GetInt32(sqlReader.GetOrdinal("Id")),
                                TournamentId       = sqlReader.GetInt32(sqlReader.GetOrdinal("TournamentId")),
                                PlayerId           = sqlReader.GetInt32(sqlReader.GetOrdinal("PlayerId")),
                                OpponentIdsBlobbed = sqlReader.GetString(sqlReader.GetOrdinal("OpponentIds")),
                                PlayerName         = sqlReader.GetString(sqlReader.GetOrdinal("PlayerName")),
                                Active             = sqlReader.GetBoolean(sqlReader.GetOrdinal("Active")),
                                Bye                = sqlReader.GetBoolean(sqlReader.GetOrdinal("Bye")),
                                ByeCount           = sqlReader.GetInt32(sqlReader.GetOrdinal("ByeCount")),
                                RoundsPlayed       = sqlReader.GetInt32(sqlReader.GetOrdinal("RoundsPlayed")),
                                Rank               = sqlReader.GetInt32(sqlReader.GetOrdinal("Rank")),
                                Score              = sqlReader.GetInt32(sqlReader.GetOrdinal("Score")),
                                MOV                = sqlReader.GetInt32(sqlReader.GetOrdinal("MOV")),
                                SOS                = sqlReader.GetDecimal(sqlReader.GetOrdinal("SOS")),
                                API_UserAccountId  = sqlReader.GetInt32(sqlReader.GetOrdinal("UserAccountId"))
                            };

                            newTournament.Players.Add(player);
                        }
                    }
                }

                using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsRounds_GET", sqlConn))
                {
                    sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@TournamentId", newTournament.Id);
                    using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
                    {
                        while (sqlReader.Read())
                        {
                            TournamentMainRound round = new TournamentMainRound
                            {
                                Id           = sqlReader.GetInt32(sqlReader.GetOrdinal("Id")),
                                TournamentId = sqlReader.GetInt32(sqlReader.GetOrdinal("TournamentId")),
                                Number       = sqlReader.GetInt32(sqlReader.GetOrdinal("Number")),
                                Swiss        = sqlReader.GetBoolean(sqlReader.GetOrdinal("Swiss"))
                            };

                            if (!sqlReader.IsDBNull(sqlReader.GetOrdinal("RoundTimeEnd")))
                            {
                                round.RoundTimeEnd = sqlReader.GetDateTime(sqlReader.GetOrdinal("RoundTimeEnd"));
                            }

                            newTournament.Rounds.Add(round);
                        }
                    }
                }

                foreach (TournamentMainRound round in newTournament.Rounds)
                {
                    using (SqlCommand sqlCmd = new SqlCommand("dbo.spTournamentsRoundsTables_GET", sqlConn))
                    {
                        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@RoundId", round.Id);
                        using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
                        {
                            while (sqlReader.Read())
                            {
                                TournamentMainRoundTable table = new TournamentMainRoundTable
                                {
                                    Id            = sqlReader.GetInt32(sqlReader.GetOrdinal("Id")),
                                    RoundId       = sqlReader.GetInt32(sqlReader.GetOrdinal("RoundId")),
                                    Number        = sqlReader.GetInt32(sqlReader.GetOrdinal("Number")),
                                    TableName     = sqlReader.GetString(sqlReader.GetOrdinal("TableName")),
                                    ScoreTied     = sqlReader.GetBoolean(sqlReader.GetOrdinal("ScoreTied")),
                                    Bye           = sqlReader.GetBoolean(sqlReader.GetOrdinal("Bye")),
                                    Player1Id     = sqlReader.GetInt32(sqlReader.GetOrdinal("Player1Id")),
                                    Player1Name   = sqlReader.GetString(sqlReader.GetOrdinal("Player1Name")),
                                    Player1Winner = sqlReader.GetBoolean(sqlReader.GetOrdinal("Player1Winner")),
                                    Player1Score  = sqlReader.GetInt32(sqlReader.GetOrdinal("Player1Score")),
                                    Player2Id     = sqlReader.GetInt32(sqlReader.GetOrdinal("Player2Id")),
                                    Player2Name   = sqlReader.GetString(sqlReader.GetOrdinal("Player2Name")),
                                    Player2Winner = sqlReader.GetBoolean(sqlReader.GetOrdinal("Player2Winner")),
                                    Player2Score  = sqlReader.GetInt32(sqlReader.GetOrdinal("Player2Score"))
                                };
                                round.Tables.Add(table);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public static void CalculatePlayerScores(ref TournamentMain objTournMain)
        {
            //All the players in the tournament should be included, regardless of being currently active in the tournament or not.

            int  intScoreDiff = 0;
            bool blnWinner    = false;

            Dictionary <int, TournamentMainPlayer> dctPlayers = new Dictionary <int, TournamentMainPlayer>();

            //Reset and calculate each player's score
            foreach (TournamentMainPlayer player in objTournMain.Players)
            {
                if (!dctPlayers.ContainsKey(player.PlayerId))
                {
                    dctPlayers.Add(player.PlayerId, new TournamentMainPlayer());
                }

                player.MOV          = 0;
                player.RoundsPlayed = 0;
                player.Score        = 0;
                player.SOS          = 0;
                player.ByeCount     = 0;
                player.OpponentIds  = new List <int>();

                //Go through each round, find their table and calculate the Margin of Victory (MOV) score
                foreach (TournamentMainRound round in objTournMain.Rounds)
                {
                    foreach (TournamentMainRoundTable table in round.Tables)
                    {
                        if ((table.Player1Id == player.PlayerId || table.Player2Id == player.PlayerId) && (table.Player1Winner || table.Player2Winner))
                        {
                            player.RoundsPlayed++;
                            blnWinner = false;

                            //Keep track of all the opponents faced for each player
                            if (table.Player1Id == player.PlayerId)
                            {
                                if (table.Player2Id > 0)
                                {
                                    player.OpponentIds.Add(table.Player2Id);
                                }
                                else if (table.Bye)
                                {
                                    player.ByeCount++;
                                }
                            }
                            else
                            {
                                player.OpponentIds.Add(table.Player1Id);
                            }

                            //Set the table's score difference and if player is the winner
                            if (table.Player1Winner)
                            {
                                intScoreDiff = table.Player1Score - table.Player2Score;
                                if (player.PlayerId == table.Player1Id)
                                {
                                    blnWinner = true;
                                }
                            }
                            else if (table.Player2Winner)
                            {
                                intScoreDiff = table.Player2Score - table.Player1Score;
                                if (player.PlayerId == table.Player2Id)
                                {
                                    blnWinner = true;
                                }
                            }

                            //Set points if score tied for the table
                            if (table.ScoreTied)
                            {
                                player.MOV += objTournMain.MaxPoints;
                            }

                            //Set score and MOV
                            if (blnWinner)
                            {
                                player.Score++;

                                if (!table.ScoreTied)
                                {
                                    player.MOV += (intScoreDiff + objTournMain.MaxPoints);
                                }
                            }
                            else
                            {
                                if (!table.ScoreTied)
                                {
                                    player.MOV += (objTournMain.MaxPoints - intScoreDiff);
                                }
                            }

                            break;
                        }
                    }
                }

                //Set player dictionary for quick access here soon
                dctPlayers[player.PlayerId] = player;
            }


            //Now calculate the Strength of Schedule (SOS)
            if (objTournMain.Rounds.Count > 0)
            {
                foreach (TournamentMainPlayer player in objTournMain.Players)
                {
                    if (player.RoundsPlayed == 0)
                    {
                        continue;
                    }

                    decimal decSoS = 0;
                    foreach (int opponentId in player.OpponentIds)
                    {
                        if (dctPlayers.ContainsKey(opponentId))
                        {
                            TournamentMainPlayer opponent = dctPlayers[opponentId];
                            if (opponent.RoundsPlayed == 0)
                            {
                                continue;
                            }
                            decSoS += Decimal.Divide(opponent.Score, opponent.RoundsPlayed);
                        }
                    }

                    decSoS    /= player.RoundsPlayed;
                    player.SOS = Math.Round(decSoS, 2);
                }
            }



            //Determine standings/rank
            List <TournamentMainPlayer> lstStandings = GetStandings(objTournMain);
            int intRank = 1;

            foreach (TournamentMainPlayer standingPlayer in lstStandings)
            {
                foreach (TournamentMainPlayer mainPlayer in objTournMain.Players)
                {
                    if (standingPlayer.PlayerId == mainPlayer.PlayerId)
                    {
                        mainPlayer.Rank = intRank;
                        break;
                    }
                }
                intRank++;
            }
        }
        //Opening
        protected override void OnAppearing()
        {
            base.OnAppearing();

            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                objTournMain = new TournamentMain();
                objTournMain = conn.GetWithChildren <TournamentMain>(intTournID, true);
                Title        = objTournMain.Name;

                UpdatePlayerList(conn);

                //Get full list of players
                List <Player> lstPlayers = conn.Query <Player>("SELECT * FROM Player WHERE (Active = 1 AND DateDeleted IS NULL) OR Id IN (" + objTournMain.ActivePlayersList() + ")");

                //Get list of currently active players in tournament
                string[] arrActivePlayers = objTournMain.ActivePlayersList().Split(',');


                //Set using the ViewModel version.  This allows being able to manipulate back and forth across the class properties, while displaying as intended on the GUI
                //while also ensuring none of the goings ons of the properties touching each other don't occur without this specific view model (such as the SQL table updates)
                int intRow = 0;
                lstViewPlayers = new ObservableCollection <PlayerToTournamentMainPlayer_ViewModel>();
                TournamentMainPlayer tmpTournamentMainPlayer = null;
                foreach (Player player in lstPlayers)
                {
                    player.Active = false;
                    if (arrActivePlayers.Contains <string>(player.Id.ToString()))
                    {
                        player.Active = true;
                    }
                    intRow++;

                    //Set the tournament player equivalent
                    tmpTournamentMainPlayer = null;
                    foreach (TournamentMainPlayer tournamentPlayer in objTournMain.Players)
                    {
                        if (tournamentPlayer.PlayerId == player.Id)
                        {
                            tmpTournamentMainPlayer = tournamentPlayer;
                            break;
                        }
                    }

                    lstViewPlayers.Add(new PlayerToTournamentMainPlayer_ViewModel(player, intTournID, intRow, tmpTournamentMainPlayer));
                }
                playersListView.ItemsSource = lstViewPlayers;
            }


            //Remove all the "Round" tabs and then repopulate them
            for (int index = this.Children.Count - 1; index > 0; index--)
            {
                if (index > 0)
                {
                    this.Children.RemoveAt(index);
                }
            }

            //Add each round as tabs
            foreach (TournamentMainRound round in objTournMain.Rounds)
            {
                Children.Add(new Tournaments_RoundInfo("Rd " + round.Number, round.Id, objTournMain.Rounds.Count));
            }

            //Remove option to delete round if there are no rounds
            if (objTournMain.Rounds.Count == 0)
            {
                ToolbarItems.Remove(deleteRoundBtn);
            }
        }
        //Start next round
        private void startRoundBtn_ToolbarItem_Activated(object sender, EventArgs e)
        {
            //Make sure we actually have players
            if (objTournMain.Players.Count == 0)
            {
                DisplayAlert("Warning!", "You must add players first to this tournament!", "D'oh!");
                return;
            }

            //Housekeeping with the latest round
            if (objTournMain.Rounds.Count > 0)
            {
                //Grab the latest information before checking the scores and calculating them
                using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                {
                    objTournMain = new TournamentMain();
                    objTournMain = conn.GetWithChildren <TournamentMain>(intTournID, true);
                }

                TournamentMainRound latestRound = objTournMain.Rounds[objTournMain.Rounds.Count - 1];

                //Before starting a new round, make sure we're not missing any scores
                foreach (TournamentMainRoundTable table in latestRound.Tables)
                {
                    if (!table.Player1Winner && !table.Player2Winner)
                    {
                        DisplayAlert("Warning!", "Verify that all tables are completed for the current round!", "D'oh!");
                        return;
                    }
                }

                Utilities.CalculatePlayerScores(ref objTournMain);
            }

            //Grab list of currently active players in the tournament
            Dictionary <int, List <TournamentMainPlayer> > dctActiveTournamentPlayerScores = new Dictionary <int, List <TournamentMainPlayer> >();

            List <TournamentMainPlayer> lstActiveTournamentPlayers      = new List <TournamentMainPlayer>();
            List <TournamentMainPlayer> lstActiveTournamentPlayers_Byes = new List <TournamentMainPlayer>();

            foreach (TournamentMainPlayer player in objTournMain.Players)
            {
                if (player.Active)
                {
                    TournamentMainPlayer roundPlayer = new TournamentMainPlayer();
                    roundPlayer.PlayerId = player.PlayerId;
                    roundPlayer.Score    = player.Score;

                    if (!player.Bye)
                    {
                        lstActiveTournamentPlayers.Add(roundPlayer);
                    }
                    else
                    {
                        lstActiveTournamentPlayers_Byes.Add(roundPlayer);
                        player.Bye = false;  //No longer has a Bye for the next round
                        player.ByeCount++;
                    }
                }
            }



            //Create a new round
            TournamentMainRound round = new TournamentMainRound();

            round.TournmentId = intTournID;
            round.Number      = objTournMain.Rounds.Count + 1;

            if (objTournMain.Rounds.Count == 0)
            {
                //First round, completely random player pairings
                lstActiveTournamentPlayers.Shuffle();
            }
            else
            {
                //Subsequent rounds, group up players with same win count as much as possible and randomize
                dctActiveTournamentPlayerScores = new Dictionary <int, List <TournamentMainPlayer> >();
                for (int i = objTournMain.Rounds.Count; i >= 0; i--)
                {
                    dctActiveTournamentPlayerScores.Add(i, new List <TournamentMainPlayer>());
                    foreach (TournamentMainPlayer activePlayer in lstActiveTournamentPlayers)
                    {
                        if (i == activePlayer.Score)
                        {
                            dctActiveTournamentPlayerScores[i].Add(activePlayer);
                        }
                    }

                    dctActiveTournamentPlayerScores[i].Shuffle(); //Shuffle all the players in each win bracket
                }

                //Clear out the active list, then go down the list and re-add them back in.
                lstActiveTournamentPlayers.Clear();
                for (int i = objTournMain.Rounds.Count; i >= 0; i--)
                {
                    if (dctActiveTournamentPlayerScores.ContainsKey(i))
                    {
                        foreach (TournamentMainPlayer activePlayer in dctActiveTournamentPlayerScores[i])
                        {
                            lstActiveTournamentPlayers.Add(activePlayer);
                        }
                    }
                }

                //If odd number of players, the last in the list will get a Bye
                //Get the lowest ranked player that hasn't had a bye already
                if (lstActiveTournamentPlayers.Count % 2 != 0)
                {
                    foreach (TournamentMainPlayer player in objTournMain.Players.OrderByDescending(obj => obj.Rank).ToList())
                    {
                        if (player.ByeCount == 0)
                        {
                            for (int i = lstActiveTournamentPlayers.Count - 1; i > 0; i--)
                            {
                                if (lstActiveTournamentPlayers[i].PlayerId == player.PlayerId)
                                {
                                    TournamentMainPlayer roundPlayer = lstActiveTournamentPlayers[i];
                                    lstActiveTournamentPlayers.RemoveAt(i);
                                    lstActiveTournamentPlayers.Add(roundPlayer);
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            }

            //Create each table, pair 'em up
            TournamentMainRoundTable roundTable = new TournamentMainRoundTable();

            foreach (TournamentMainPlayer player in lstActiveTournamentPlayers)
            {
                if (roundTable.Player1Id != 0 && roundTable.Player2Id != 0)
                {
                    setRoundTableNames(ref roundTable);
                    round.Tables.Add(roundTable);
                    roundTable = new TournamentMainRoundTable();
                }

                if (roundTable.Player1Id == 0)
                {
                    roundTable.Number    = round.Tables.Count + 1;
                    roundTable.Player1Id = player.PlayerId;
                }
                else if (roundTable.Player2Id == 0)
                {
                    roundTable.Player2Id = player.PlayerId;
                }
            }

            //If the last table of non-manual byes is an odd-man, set table/player as a bye
            if (roundTable.Player2Id == 0)
            {
                roundTable.Bye           = true;
                roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                roundTable.Player1Winner = true;

                foreach (TournamentMainPlayer player in objTournMain.Players)
                {
                    if (player.Id == roundTable.Player2Id)
                    {
                        player.ByeCount++;
                        break;
                    }
                }
            }

            setRoundTableNames(ref roundTable);
            round.Tables.Add(roundTable);


            //If a manual bye (such as first-round byes at a tournament), add these players now
            if (lstActiveTournamentPlayers_Byes.Count > 0)
            {
                lstActiveTournamentPlayers_Byes.Shuffle();
                foreach (TournamentMainPlayer player in lstActiveTournamentPlayers_Byes)
                {
                    roundTable               = new TournamentMainRoundTable();
                    roundTable.Number        = round.Tables.Count + 1;
                    roundTable.Player1Id     = player.PlayerId;
                    roundTable.Bye           = true;
                    roundTable.Player1Score  = objTournMain.MaxPoints / 2;
                    roundTable.Player1Winner = true;
                    setRoundTableNames(ref roundTable);
                    round.Tables.Add(roundTable);
                }
            }

            //Add/Save the round
            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
            {
                try
                {
                    conn.Update(objTournMain); //Update any other information that was saved such as Bye counts and such
                    conn.InsertWithChildren(round, true);
                }
                catch (Exception ex)
                {
                    DisplayAlert("Warning!", "Error adding round to tournament! " + ex.Message, "OK");
                }

                OnAppearing();
            }
        }
Ejemplo n.º 10
0
        public ActionResult AddNewRound(bool swiss, int topCut, string activePlayers)
        {
            List <TournamentMainPlayer> result = JsonConvert.DeserializeObject <List <TournamentMainPlayer> >(activePlayers);

            //Flag each current player as inactive
            foreach (TournamentMainPlayer currentPlayer in objTournMain.Players)
            {
                currentPlayer.Active = false;
            }

            //Then determine which, if any, should be active.
            foreach (TournamentMainPlayer resultPlayer in result)
            {
                foreach (TournamentMainPlayer currentPlayer in objTournMain.Players)
                {
                    if (currentPlayer.PlayerId == resultPlayer.PlayerId)
                    {
                        resultPlayer.Id      = currentPlayer.Id;
                        currentPlayer.Active = true;
                        currentPlayer.Bye    = resultPlayer.Bye;
                        break;
                    }
                }
            }

            //Determine if there are any new players to be added
            foreach (TournamentMainPlayer resultPlayer in result)
            {
                if (resultPlayer.Id == 0)
                {
                    foreach (Player player in lstPlayersAll)
                    {
                        if (player.Id == resultPlayer.PlayerId)
                        {
                            TournamentMainPlayer newNextRoundPlayer = new TournamentMainPlayer
                            {
                                Id           = 0,
                                TournamentId = tournamentId,
                                PlayerId     = player.Id,
                                PlayerName   = player.Name,
                                Active       = true,
                                Bye          = resultPlayer.Bye
                            };

                            objTournActivity.TournamentMain.Players.Add(newNextRoundPlayer);
                        }
                    }
                }
            }

            var request = new RestRequest("TournamentsPlayers/{userid}/{id}", Method.PUT);

            request.AddUrlSegment("userid", Utilities.CurrentUser.Id);
            request.AddUrlSegment("id", tournamentId);
            request.AddJsonBody(JsonConvert.SerializeObject(objTournActivity.TournamentMain));

            // execute the request
            IRestResponse response = client.Execute(request);
            var           content  = response.Content;

            //Start up the next round
            StartRound(swiss, topCut);

            return(View(objTournActivity));
        }
Ejemplo n.º 11
0
        public static async System.Threading.Tasks.Task <string> ImportAllAsync()
        {
            client = Utilities.InitializeRestClient();

            if (App.IsUserLoggedIn)
            {
                try
                {
                    //Get the current players saved locally
                    List <Player>         lstCurrentPlayers     = new List <Player>();
                    List <TournamentMain> lstCurrentTournaments = new List <TournamentMain>();

                    using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                    {
                        Utilities.InitializeTournamentMain(conn);

                        lstCurrentPlayers     = conn.Query <Player>("SELECT * FROM Player WHERE Active = ? AND DateDeleted IS NULL ORDER BY Name", true);
                        lstCurrentTournaments = conn.Query <TournamentMain>("SELECT * FROM TournamentMain WHERE DateDeleted IS NULL ORDER BY StartDate");
                    }

                    //Import general Players and general Tournament info
                    await ImportPlayersAsync(lstCurrentPlayers);
                    await ImportTournamentsAsync(lstCurrentTournaments);


                    //Import specific player, round, and table data for each tournament
                    using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))
                    {
                        //Collect most up-to-date Player info since they've been imported, collecting API Ids
                        lstCurrentPlayers = new List <Player>();
                        lstCurrentPlayers = conn.Query <Player>("SELECT * FROM Player WHERE Active = ? AND DateDeleted IS NULL ORDER BY Name", true);

                        Dictionary <int, int> dctAPIPlayerId = new Dictionary <int, int>();
                        foreach (Player player in lstCurrentPlayers)
                        {
                            if (!dctAPIPlayerId.ContainsKey(player.API_Id))
                            {
                                dctAPIPlayerId.Add(player.API_Id, player.Id);
                            }
                        }


                        lstCurrentTournaments = new List <TournamentMain>();
                        lstCurrentTournaments = conn.Query <TournamentMain>("SELECT * FROM TournamentMain WHERE DateDeleted IS NULL ORDER BY StartDate");

                        //Go through each saved Tournament on device, pulling the detailed round/table data for each
                        TournamentMain objTournMain;
                        foreach (TournamentMain localTournament in lstCurrentTournaments)
                        {
                            objTournMain = new TournamentMain();
                            objTournMain = conn.GetWithChildren <TournamentMain>(localTournament.Id, true);

                            if (objTournMain.API_Id > 0)
                            {
                                var request = new RestRequest("Tournaments/{userid}/{id}", Method.GET);
                                request.AddUrlSegment("userid", App.CurrentUser.Id);
                                request.AddUrlSegment("id", objTournMain.API_Id);

                                // execute the request
                                var response = await client.ExecuteTaskAsync(request);

                                var content = response.Content;

                                List <TournamentMain> result = JsonConvert.DeserializeObject <List <TournamentMain> >(JsonConvert.DeserializeObject(content).ToString());
                                foreach (TournamentMain ApiTournament in result)
                                {
                                    //Add/update Tournament Player data
                                    foreach (TournamentMainPlayer ApiTournPlayer in ApiTournament.Players)
                                    {
                                        TournamentMainPlayer updatePlayer = new TournamentMainPlayer()
                                        {
                                            Active       = ApiTournPlayer.Active,
                                            API_Id       = ApiTournPlayer.Id,
                                            Bye          = ApiTournPlayer.Bye,
                                            ByeCount     = ApiTournPlayer.ByeCount,
                                            MOV          = ApiTournPlayer.MOV,
                                            PlayerId     = (dctAPIPlayerId.ContainsKey(ApiTournPlayer.PlayerId) ? dctAPIPlayerId[ApiTournPlayer.PlayerId] : 0),
                                            PlayerName   = ApiTournPlayer.PlayerName,
                                            Rank         = ApiTournPlayer.Rank,
                                            RoundsPlayed = ApiTournPlayer.RoundsPlayed,
                                            TournamentId = objTournMain.Id
                                        };

                                        foreach (TournamentMainPlayer localPlayer in objTournMain.Players)
                                        {
                                            if (localPlayer.PlayerId == updatePlayer.PlayerId)
                                            {
                                                updatePlayer.Id = localPlayer.Id;
                                                break;
                                            }
                                        }

                                        if (updatePlayer.Id == 0)
                                        {
                                            conn.Insert(updatePlayer);
                                        }
                                        else
                                        {
                                            conn.Update(updatePlayer);
                                        }
                                    }

                                    //Add/Update/Delete Rounds
                                    foreach (TournamentMainRound ApiRound in ApiTournament.Rounds)
                                    {
                                        TournamentMainRound updateRound = new TournamentMainRound()
                                        {
                                            API_Id       = ApiRound.Id,
                                            Number       = ApiRound.Number,
                                            RoundTimeEnd = ApiRound.RoundTimeEnd,
                                            Swiss        = ApiRound.Swiss,
                                            TournamentId = objTournMain.Id
                                        };

                                        //Grab the device's SQL round Id
                                        foreach (TournamentMainRound localRound in objTournMain.Rounds)
                                        {
                                            if (localRound.API_Id == updateRound.API_Id)
                                            {
                                                updateRound.Id = localRound.Id;
                                                break;
                                            }
                                        }
                                        if (updateRound.Id == 0)
                                        {
                                            conn.Insert(updateRound);
                                            TournamentMainRound tmp = conn.Query <TournamentMainRound>("SELECT * FROM TournamentMainRound WHERE TournamentId = ? ORDER BY Id DESC", updateRound.TournamentId)[0];
                                            updateRound.Id = tmp.Id; //We need this latest RoundId so that the tables will be associated with the correct round
                                        }
                                        else
                                        {
                                            conn.Update(updateRound);
                                        }


                                        //Add/update table data
                                        foreach (TournamentMainRoundTable ApiTable in ApiRound.Tables)
                                        {
                                            TournamentMainRoundTable updateTable = new TournamentMainRoundTable()
                                            {
                                                API_Id        = ApiTable.Id,
                                                Bye           = ApiTable.Bye,
                                                Number        = ApiTable.Number,
                                                Player1Id     = (dctAPIPlayerId.ContainsKey(ApiTable.Player1Id) ? dctAPIPlayerId[ApiTable.Player1Id] : 0),
                                                Player1Name   = ApiTable.Player1Name,
                                                Player1Score  = ApiTable.Player1Score,
                                                Player1Winner = ApiTable.Player1Winner,
                                                Player2Id     = (dctAPIPlayerId.ContainsKey(ApiTable.Player2Id) ? dctAPIPlayerId[ApiTable.Player2Id] : 0),
                                                Player2Name   = ApiTable.Player2Name,
                                                Player2Score  = ApiTable.Player2Score,
                                                Player2Winner = ApiTable.Player2Winner,
                                                ScoreTied     = ApiTable.ScoreTied,
                                                TableName     = ApiTable.TableName,
                                                RoundId       = updateRound.Id
                                            };


                                            //Grab the device's SQL table Id
                                            foreach (TournamentMainRound localRound in objTournMain.Rounds)
                                            {
                                                if (localRound.Id == updateTable.RoundId)
                                                {
                                                    foreach (TournamentMainRoundTable localTable in localRound.Tables)
                                                    {
                                                        if (localTable.API_Id == updateTable.API_Id)
                                                        {
                                                            updateTable.Id = localTable.Id;
                                                            break;
                                                        }
                                                    }
                                                    break;
                                                }
                                            }

                                            if (updateTable.Id == 0)
                                            {
                                                conn.Insert(updateTable);
                                            }
                                            else
                                            {
                                                conn.Update(updateTable);
                                            }
                                        }
                                    }

                                    //Delete any local rounds that are saved, but were removed online
                                    foreach (TournamentMainRound localRound in objTournMain.Rounds)
                                    {
                                        bool blnDeleteRound = true;
                                        foreach (TournamentMainRound ApiRound in ApiTournament.Rounds)
                                        {
                                            if (ApiRound.Id == localRound.API_Id)
                                            {
                                                blnDeleteRound = false;
                                                break;
                                            }
                                        }
                                        if (blnDeleteRound)
                                        {
                                            conn.Delete(localRound);
                                        }
                                    }

                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("Error:" + ex.Message);
                    return("Error: " + ex.Message);
                }

                return("Import success");
            }

            return("");
        }