Ejemplo n.º 1
0
        public static string ToString(TournamentState state)
        {
            switch (state)
            {
            case TournamentState.All:
                return("all");

            case TournamentState.Pending:
                return("pending");

            case TournamentState.In_Progress:
                return("in_progress");

            case TournamentState.Complete:
                return("complete");

            case TournamentState.Awaiting_Review:
                return("awaiting_review");

            case TournamentState.Checking_In:
                return("checking_in");

            default:
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 2
0
        public void TrySetCurrentTournamentWithNoCurrentTournament()
        {
            TournamentsManager manager = new TournamentsManager()
            {
                GuildId = 1
            };

            TournamentState state      = new TournamentState(1, DefaultTournamentName);
            TournamentState otherState = new TournamentState(1, DefaultTournamentName + "2");

            manager.AddOrUpdateTournament(DefaultTournamentName, state, (name, oldState) => oldState);

            Assert.IsTrue(
                manager.TrySetCurrentTournament(DefaultTournamentName, out string errorMessage),
                "Couldn't set current tournament.");
            manager.TryReadActionOnCurrentTournament(currentState =>
            {
                Assert.AreEqual(DefaultTournamentName, currentState.Name, "Unexpected tournament in TryReadAction");
                return(Task.CompletedTask);
            });
            manager.TryReadWriteActionOnCurrentTournament(currentState =>
            {
                Assert.AreEqual(
                    DefaultTournamentName, currentState.Name, "Unexpected tournament in TryReadWriteAction (Action)");
            });
            manager.TryReadWriteActionOnCurrentTournament(currentState =>
            {
                Assert.AreEqual(
                    DefaultTournamentName, currentState.Name, "Unexpected tournament in TryReadWriteAction (Func)");
                return(Task.CompletedTask);
            });
        }
Ejemplo n.º 3
0
 public Tournament(int rounds)
 {
     this.rounds          = rounds;
     this.courrentRound   = 1;
     this.tournamentState = TournamentState.NewGame;
     this.players         = new List <Player>();
 }
Ejemplo n.º 4
0
        protected override void Render(HtmlTextWriter writer)
        {
            if (InvalidTournamentType)
            {
                WriteIndex(writer);
                return;
            }

            TournamentState state = TournamentState.NotStarted;
            Tournament      tour  = GetTournament();

            if (tour != null)
            {
                state = tour.State;
            }

            createBattle.Visible = button.Visible = (state == TournamentState.NotStarted);

            InitTournamentViewer();

            WriteBasicOptions(writer);
            WriteUnits(writer, tour);
            WriteState(writer, tour);

            StateViewer viewer = (StateViewer)States[state];

            if (viewer == null)
            {
                writer.WriteLine("Ups... don't know how to handle `{0}'", state);
                return;
            }

            viewer(writer, tour);
            base.Render(writer);
        }
Ejemplo n.º 5
0
 public Tournament(int rounds )
 {
     this.rounds = rounds;
     this.courrentRound = 1;
     this.tournamentState = TournamentState.NewGame;
     this.players = new List<Player>();
 }
Ejemplo n.º 6
0
        public IActionResult Update(Guid id, [FromBody] JsonPatchDocument <TournamentStateUpdateModel> jsonPatchDocument)
        {
            // Get the tournament
            Tournament tournament = this.TournamentRepository.Get(id);

            if (tournament == null)
            {
                return(NotFound());
            }

            // Get the current tournament status
            TournamentState initialState = tournament.State;

            // Update the tournament
            TournamentStateUpdateModel tournamentUpdate = new TournamentStateUpdateModel();

            jsonPatchDocument.ApplyTo(tournamentUpdate);

            // Only honour the update of a state
            if (tournamentUpdate.State != initialState)
            {
                // Set tournament state based on logic rules
                SetState(tournament, initialState, tournamentUpdate);

                // Update the tournament state
                this.TournamentRepository.Update(tournament);
            }


            // Return success
            return(NoContent());
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> AddTournamentStateBell(Guid id)
        {
            Tournament tournament = this.TournamentRepository.Get(id);

            if (tournament == null)
            {
                return(NotFound());
            }
            // Get the current tournament status
            TournamentState initialState = tournament.State;

            TournamentStateUpdateModel tournamentStateChange = this.TournamentLogic.AddBell(tournament);

            // Set tournament state based on logic rules
            SetState(tournament, initialState, tournamentStateChange);

            // Update the tournament state
            this.TournamentRepository.Update(tournament);

            // Broadcast to all subscribers that the state has changed
            if (initialState != tournamentStateChange.State)
            {
                await this.TournamentBroadcast.TournamentStateChangeAsync(id, tournament.State, tournament.PreplayGameId, tournament.InplayGameId, tournament.PostplayGameId);
            }

            // Return the updated tournament
            return(Ok(Mapper.Map <Tournament, TournamentModel>(this.TournamentRepository.Get(id))));
        }
Ejemplo n.º 8
0
        public void SaveTournament()
        {
            // Arrange
            var tournamentRepositoryMock = new Mock <ITournamentRepository>();
            var mapper     = Helper.SetupMapper();
            var tournament = new Tournament {
                Id             = new Guid(),
                PreplayGameId  = null,
                InplayGameId   = null,
                PostplayGameId = null,
                CluesPerGame   = 1
            };

            tournamentRepositoryMock.Setup(p => p.Get(It.IsAny <Guid>())).Returns(tournament);
            var             gameLogicFake           = new Mock <IGameLogic>();
            var             tournamnetLogicFake     = new Mock <ITournamentLogic>();
            var             tournamentBroadcastFake = new Mock <ITournamentBroadcast>();
            var             tournamentController    = new TournamentController(tournamentRepositoryMock.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
            TournamentState currentState            = tournament.State;

            // Act
            var actionResult = tournamentController.Update(new Guid(), new JsonPatchDocument <TournamentStateUpdateModel>().Replace(t => t.State, TournamentState.PrePlay));

            tournamentRepositoryMock.Verify(mocks => mocks.Update(It.IsAny <Tournament>()), Times.Once);
        }
        public Tournament(string name)
        {
            Teams   = new List <string>();
            Matches = new List <Match>();
            state   = TournamentState.New;

            this.Name = name;
        }
Ejemplo n.º 10
0
 public void AddRound()
 {
     this.courrentRound++;
     if(this.courrentRound>=this.rounds)
     {
         this.tournamentState = TournamentState.Ended;
     }
 }
Ejemplo n.º 11
0
 public void AddRound()
 {
     this.courrentRound++;
     if (this.courrentRound >= this.rounds)
     {
         this.tournamentState = TournamentState.Ended;
     }
 }
Ejemplo n.º 12
0
        public async Task ScheduleRequiresMultipleEmbeds()
        {
            const int teamsCount   = 50;
            const int readersCount = teamsCount / 2;

            MessageStore             messageStore  = new MessageStore();
            ICommandContext          context       = this.CreateCommandContext(messageStore, guildId: DefaultGuildId);
            GlobalTournamentsManager globalManager = new GlobalTournamentsManager();
            TournamentsManager       manager       = globalManager.GetOrAdd(DefaultGuildId, id => new TournamentsManager());

            HashSet <Team> teams = new HashSet <Team>(
                Enumerable.Range(1, teamsCount).Select(id => new Team()
            {
                Name = $"#Team{id}"
            }));
            HashSet <Reader> readers = new HashSet <Reader>(
                Enumerable.Range(1, readersCount).Select(id => new Reader()
            {
                Id = (ulong)id, Name = $"#Reader{id}"
            }));

            RoundRobinScheduleFactory factory = new RoundRobinScheduleFactory(1, 0);
            Schedule schedule = factory.Generate(teams, readers);

            ITournamentState state = new TournamentState(DefaultGuildId, "T");

            state.Schedule = schedule;
            manager.AddOrUpdateTournament(state.Name, state, (name, oldState) => oldState);
            Assert.IsTrue(
                manager.TrySetCurrentTournament(state.Name, out string errorMessage),
                $"Failed to set the tournament: '{errorMessage}'");
            globalManager.GetOrAdd(DefaultGuildId, id => manager);

            BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager);

            await commandHandler.GetScheduleAsync();

            Assert.IsTrue(
                messageStore.ChannelEmbeds.Count > 1,
                $"Expected more than 1 embed, got {messageStore.ChannelEmbeds.Count}");

            string allEmbeds = string.Join('\n', messageStore.ChannelEmbeds);

            for (int round = 0; round < schedule.Rounds.Count; round++)
            {
                Assert.IsTrue(
                    allEmbeds.Contains(BotStrings.RoundNumber(round + 1)),
                    $"Round {round + 1} not found in the embeds. Embeds: '{allEmbeds}'");
                foreach (Game game in schedule.Rounds[round].Games)
                {
                    string expectedGame = BotStrings.ScheduleLine(
                        game.Reader.Name, game.Teams.Select(team => team.Name).ToArray());
                    Assert.IsTrue(
                        allEmbeds.Contains(expectedGame),
                        $"Game '{expectedGame}' not foudn in embed. Embed: '{allEmbeds}'");
                }
            }
        }
Ejemplo n.º 13
0
 public Tournament(
     TournamentState currentState,
     TournamentRules rules,
     IEnumerable <Guid> contestants)
 {
     _state            = new BehaviorSubject <TournamentState>(currentState);
     _rules            = rules;
     _contestantsGuids = contestants.ToArray();
 }
Ejemplo n.º 14
0
        public bool Score(int selectedMatch, int score1, int score2)
        {
            var match = Matches[selectedMatch];

            if (match.State == MatchState.Ended)
            {
                return(false);
            }

            if (score1 == score2)
            {
                return(false);
            }

            string matchWinner;

            if (score1 > score2)
            {
                matchWinner = match.Team1;
            }
            else
            {
                matchWinner = match.Team2;
            }

            match.Score1 = score1;
            match.Score2 = score2;
            match.State  = MatchState.Ended;

            //Select a match that only have one team(is considered a Open Match)
            //If dont exist, create a new one
            var nextMatch = Matches.Where(m => m.State == MatchState.Open).FirstOrDefault();

            if (nextMatch == null)
            {
                nextMatch = new Match(matchWinner, String.Empty, MatchState.Open);
                Matches.Add(nextMatch);
            }
            else
            {
                nextMatch.Team2 = matchWinner;
                nextMatch.State = MatchState.Closed;
            }

            //If the collection dont have any Closed Match avaiable,
            //that means all the matches are ended and this winner is the Tournament Winner
            if (!Matches.Any(m => m.State == MatchState.Closed))
            {
                Winner = matchWinner;
                state  = TournamentState.Ended;
                return(true);
            }

            return(true);
        }
Ejemplo n.º 15
0
 public async Task TournamentStateChangeAsync(Guid id, TournamentState state, Guid?preplayGameId, Guid?inplayGameId, Guid?postplayGameId)
 {
     await this.TournamentHub.Clients.Group(id.ToString()).SendAsync("TournamentUpdate", new
     {
         Id             = id,
         State          = state,
         PreplayGameId  = preplayGameId,
         InplayGameId   = inplayGameId,
         PostplayGameId = postplayGameId,
     });
 }
Ejemplo n.º 16
0
 public void EndCurrentMatch()
 {
     state = TournamentState.IDLE;
     doneMatches.Add(currentMatch);
     if (doneMatches.Count >= nbMatches)
     {
         currentMatch = null;
         state        = TournamentState.FINISHED;
     }
     else
     {
         currentMatch = new MatchSave(PlayerSave.CreateRandomCPU(1 + doneMatches.Count * 5));
     }
 }
Ejemplo n.º 17
0
        private void SetState(Tournament tournament, TournamentState initialState, TournamentStateUpdateModel tournamentUpdate)
        {
            // If the current state is No play then treat any state change as an update to PrePlay
            if (initialState == TournamentState.NoPlay)
            {
                tournamentUpdate.State = TournamentState.PrePlay;
            }

            Game newPreplayGame;

            // Apply logic rules to state change
            switch (tournamentUpdate.State)
            {
            // Updating to preplay
            case TournamentState.PrePlay:
                // Apply the rules for setting the new Preplay state
                tournament = this.TournamentLogic.SetPreplay(tournament, out newPreplayGame);
                // Save the new preplay if one is created
                if (newPreplayGame != null)
                {
                    this.TournamentRepository.UpdateGame(newPreplayGame);
                }
                break;

            // Updating to preplay
            case TournamentState.InPlay:
                // Apply the rules for setting the new Inplay state
                tournament = this.TournamentLogic.SetInplay(tournament, out newPreplayGame);
                // Save the new preplay if one is created
                if (newPreplayGame != null)
                {
                    this.TournamentRepository.UpdateGame(newPreplayGame);
                }
                break;

            // Updating to post play
            case TournamentState.PostPlay:
                // Apply the rules for setting the new Inplay state
                tournament = this.TournamentLogic.SetPostplay(tournament, out newPreplayGame);
                // Save the new preplay if one is created
                if (newPreplayGame != null)
                {
                    this.TournamentRepository.UpdateGame(newPreplayGame);
                }
                break;

            default:
                break;
            }
        }
Ejemplo n.º 18
0
        protected ITournamentState AddCurrentTournament(
            GlobalTournamentsManager globalManager,
            ulong guildId         = DefaultGuildId,
            string tournamentName = DefaultTournamentName)
        {
            TournamentsManager manager = globalManager.GetOrAdd(guildId, id => new TournamentsManager());
            ITournamentState   state   = new TournamentState(guildId, tournamentName);

            state = manager.AddOrUpdateTournament(tournamentName, state, (name, oldState) => state);
            Assert.IsTrue(
                manager.TrySetCurrentTournament(tournamentName, out string errorMessage),
                "We should be able to set the current tournament.");
            return(state);
        }
Ejemplo n.º 19
0
        public void TryGetTournament()
        {
            TournamentsManager manager = new TournamentsManager()
            {
                GuildId = 1
            };

            Assert.IsFalse(
                manager.TryGetTournament(DefaultTournamentName, out ITournamentState state), "No tournament state should exist.");

            TournamentState newState = new TournamentState(1, DefaultTournamentName);

            manager.AddOrUpdateTournament(DefaultTournamentName, newState, (name, oldState) => oldState);
            Assert.IsTrue(manager.TryGetTournament(DefaultTournamentName, out state), "Tournament state should exist.");
            Assert.AreEqual(newState, state, "Wrong tournament retrieved.");
        }
Ejemplo n.º 20
0
        public void Start()
        {
            state = TournamentState.Started;

            for (int i = 0; i <= Teams.Count - 1; i = i + 2)
            {
                if (i == Teams.Count - 1)
                {
                    Matches.Add(new Match(Teams[i], String.Empty, MatchState.Open)); //In case of odd team number
                }
                else
                {
                    Matches.Add(new Match(Teams[i], Teams[i + 1], MatchState.Closed));
                }
            }
        }
        private void handleTournamentCreated(ResponseStatus status, IIncommingMessage rawMsg)
        {
            string msg = rawMsg.AsString();

            print("Tournament Created: " + status + "  :" + msg);
            if (waitingForResponse == false)
            {
                return;
            }

            waitingForResponse = false;
            if (status == ResponseStatus.Success)
            {
                currentTournamentID = msg;
                state = TournamentState.Lobby;
            }
        }
Ejemplo n.º 22
0
        public static string TournamentStateConverter(TournamentState tournamentState)
        {
            switch (tournamentState)
            {
            case TournamentState.All:
                return("all");

            case TournamentState.Pending:
                return("pending");

            case TournamentState.InProgress:
                return("in_progress");

            case TournamentState.Ended:
                return("ended");
            }

            return(null);
        }
Ejemplo n.º 23
0
        public static string ToString(TournamentState state)
        {
            switch (state)
            {
            case TournamentState.All:
                return("all");

            case TournamentState.Pending:
                return("pending");

            case TournamentState.InProgress:
                return("in_progress");

            case TournamentState.Ended:
                return("ended");

            default:
                throw new NotSupportedException();
            }
        }
Ejemplo n.º 24
0
        public Task AddTournamentDirectorAsync(IGuildUser newDirector, string tournamentName)
        {
            Verify.IsNotNull(newDirector, nameof(newDirector));

            if (string.IsNullOrWhiteSpace(tournamentName))
            {
                this.Logger.Debug("Did not add {id} to tournament with blank name", newDirector.Id);
                return(Task.CompletedTask);
            }

            TournamentsManager manager = this.GlobalManager.GetOrAdd(this.Context.Guild.Id, CreateTournamentsManager);

            ITournamentState state            = new TournamentState(this.Context.Guild.Id, tournamentName.Trim());
            bool             updateSuccessful = state.TryAddDirector(newDirector.Id);

            manager.AddOrUpdateTournament(
                tournamentName,
                state,
                (name, tournamentState) =>
            {
                updateSuccessful = tournamentState.TryAddDirector(newDirector.Id);
                return(tournamentState);
            });

            // TODO: Need to handle this differently depending on the stage. Completed shouldn't do anything, and
            // after RoleSetup we should give them the TD role.
            if (updateSuccessful)
            {
                this.Logger.Debug(
                    "Added {id} as a tournament director for {tournamentName}", newDirector.Id, tournamentName);
                return(this.SendChannelMessage(
                           BotStrings.AddTournamentDirectorSuccessful(tournamentName, this.Context.Guild.Name)));
            }

            this.Logger.Debug(
                "{id} already a tournament director for {tournamentName}", newDirector.Id, tournamentName);
            return(this.SendChannelMessage(
                       BotStrings.UserAlreadyTournamentDirector(tournamentName, this.Context.Guild.Name)));
        }
Ejemplo n.º 25
0
 public Tournament()
 {
     _rules            = new TournamentRules();
     _state            = new BehaviorSubject <TournamentState>(TournamentState.Created());
     _contestantsGuids = new Guid[_rules.MaxContestantsCount()];
     _machine          = new StateMachine <TournamentState, Trigger>(() => _state.Value,
                                                                     newState => _state.OnNext(newState));
     _machine.Configure(TournamentState.Created())
     .Permit(Trigger.StartTournament, TournamentState.TournamentInProgress.FirstWave());
     _machine.Configure(TournamentState.TournamentInProgress.FirstWave())
     .Permit(Trigger.Cancel, TournamentState.Cancelled())
     .Permit(Trigger.MoveToNextWave, TournamentState.TournamentInProgress.SecondWave());
     _machine.Configure(TournamentState.TournamentInProgress.SecondWave())
     .Permit(Trigger.Cancel, TournamentState.Cancelled())
     .Permit(Trigger.MoveToNextWave, TournamentState.TournamentInProgress.SemiFinal());
     _machine.Configure(TournamentState.TournamentInProgress.SemiFinal())
     .Permit(Trigger.Cancel, TournamentState.Cancelled())
     .Permit(Trigger.MoveToNextWave, TournamentState.TournamentInProgress.Final());
     _machine.Configure(TournamentState.TournamentInProgress.Final())
     .Permit(Trigger.Cancel, TournamentState.Cancelled())
     .Permit(Trigger.Finish, TournamentState.Finished());
 }
Ejemplo n.º 26
0
        public void AddOrUpdateTournamentAddsThenUpdates()
        {
            const string       originalTournamentName = "Tournament1";
            const string       updatedTournamentName  = "Tournament2";
            TournamentsManager manager = new TournamentsManager()
            {
                GuildId = 1
            };

            TournamentState originalState = new TournamentState(1, originalTournamentName);

            string[] expectedNames = new string[] { originalTournamentName, updatedTournamentName };

            for (int i = 0; i < expectedNames.Length; i++)
            {
                ITournamentState state = manager.AddOrUpdateTournament(
                    originalTournamentName,
                    originalState,
                    (name, oldState) => new TournamentState(1, updatedTournamentName));
                Assert.AreEqual(
                    expectedNames[i], state.Name, $"Unexpected tournament returned after {i + 1} call(s).");
            }
        }
Ejemplo n.º 27
0
        public void TrySetCurrentTournamentWhenCurrentTournamentAlreadyExists()
        {
            const string       otherTournamentName = DefaultTournamentName + "2";
            TournamentsManager manager             = new TournamentsManager()
            {
                GuildId = 1
            };

            TournamentState state      = new TournamentState(1, DefaultTournamentName);
            TournamentState otherState = new TournamentState(1, otherTournamentName);

            manager.AddOrUpdateTournament(DefaultTournamentName, state, (name, oldState) => oldState);
            manager.AddOrUpdateTournament(otherTournamentName, otherState, (name, oldState) => oldState);

            Assert.IsTrue(
                manager.TrySetCurrentTournament(DefaultTournamentName, out string errorMessage),
                "First TrySet should succeed.");
            Assert.IsFalse(
                manager.TrySetCurrentTournament(otherTournamentName, out errorMessage),
                "Shouldn't be able to set the current tournament when one is already set.");
            // TODO: If we go to using resources or string consts, check that value instead of just checking that the
            // message isn't null.
            Assert.IsNotNull(errorMessage, "Error message should not be null.");
        }
Ejemplo n.º 28
0
        public void TryClearCurrentTournament()
        {
            const string       otherTournamentName = DefaultTournamentName + "2";
            TournamentsManager manager             = new TournamentsManager()
            {
                GuildId = 1
            };

            TournamentState state      = new TournamentState(1, DefaultTournamentName);
            TournamentState otherState = new TournamentState(1, otherTournamentName);

            manager.AddOrUpdateTournament(DefaultTournamentName, state, (name, oldState) => oldState);
            manager.AddOrUpdateTournament(otherTournamentName, otherState, (name, oldState) => oldState);

            Assert.IsTrue(
                manager.TrySetCurrentTournament(DefaultTournamentName, out string errorMessage),
                "Couldn't set current tournament initially.");
            Assert.IsTrue(manager.TryClearCurrentTournament(), "Couldn't clear current tournament.");

            // TrySetCurrentTournament should work again if we've just cleared it.
            Assert.IsTrue(
                manager.TrySetCurrentTournament(otherTournamentName, out errorMessage),
                "Couldn't set current tournament after clearing it.");
        }
        public async Task <IActionResult> Create([Bind("Id,Name,Date,Location,NumberOfRounds")] Tournament tournament)
        {
            //Get players unassigned to games
            var players = await _context.Players
                          .Include(p => p.MyGames)
                          .Include(p => p.TheirGames).ToListAsync();

            var unassignedPlayers = players.Where(p => p.MyGames == null || p.MyGames.Count() == 0 && p.TheirGames == null || p.TheirGames.Count() == 0).ToList();

            if (unassignedPlayers.Count < 6)
            {
                return(View("NoPlayers"));
            }

            if (tournament.NumberOfRounds > (unassignedPlayers.Count() + 1) / 2)
            {
                return(View("TooManyRounds"));
            }

            var user = await GetCurrentUserAsync();

            tournament.userId = user.Id;

            // Create new tournament and round
            Round round = null;

            if (ModelState.IsValid)
            {
                _context.Add(tournament);
                await _context.SaveChangesAsync();

                Round newRound = new Round()
                {
                    Number       = 1,
                    TournamentId = tournament.Id
                };

                _context.Add(newRound);
                await _context.SaveChangesAsync();

                round = newRound;
            }

            TournamentState.setcurrentTournament(tournament);
            TournamentState.currentRound.Number = 1;

            // If number of players is odd, find or generate a 'bye' player

            if (unassignedPlayers.Count % 2 != 0)
            {
                var byePlayerOrNull = players.SingleOrDefault(p => p.LastName == "Bye");
                if (byePlayerOrNull == null)
                {
                    var byePlayer = new Player()
                    {
                        FirstName = " ",
                        LastName  = "Bye",
                    };
                    _context.Add(byePlayer);
                    await _context.SaveChangesAsync();

                    unassignedPlayers.Add(byePlayer);
                }
                else
                {
                    unassignedPlayers.Add(byePlayerOrNull);
                }
            }

            foreach (var player in unassignedPlayers)
            {
                TournamentState.currentPlayers.Add(player);
            }

            //Sort players randomly

            var rand          = new Random();
            var randomPlayers = unassignedPlayers.OrderBy(p => rand.NextDouble()).ToList();
            int numberOfGames = randomPlayers.Count / 2;

            var bye = randomPlayers.Find(p => p.LastName == "Bye");

            //Assign players to games, create tables
            for (int i = 0; i < numberOfGames; i++)
            {
                var newTable = new PhysicalTable();
                newTable.Number = i + 1;
                _context.Add(newTable);
                await _context.SaveChangesAsync();

                var game = new Game();
                game.PhysicalTableId = newTable.Id;
                game.RoundId         = round.Id;
                game.PlayerOneId     = randomPlayers[0].Id;
                randomPlayers.Remove(randomPlayers[0]);
                game.PlayerTwoId = randomPlayers[0].Id;
                randomPlayers.Remove(randomPlayers[0]);

                //The opponent of the bye player automatically wins
                if (bye != null)
                {
                    if (game.PlayerOneId == bye.Id)
                    {
                        game.PlayerTwoScore = 1;
                    }
                    else if (game.PlayerTwoId == bye.Id)
                    {
                        game.PlayerOneScore = 1;
                    }
                }
                _context.Add(game);
            }

            await _context.SaveChangesAsync();

            return(RedirectToAction("IndexUncompleted", "Games"));
        }
Ejemplo n.º 30
0
        public IEnumerable <TournamentSummary> GetAll(TournamentState state)
        {
            var domainState = Mapper.Map <Domain.Tournaments.TournamentState>(state);

            return(Mapper.Map <IEnumerable <TournamentSummary> >(this.UnitOfWork.Tournaments.Get(domainState)));
        }
Ejemplo n.º 31
0
        public async Task SimplestSchedule()
        {
            const string readerName     = "#Reader";
            const string firstTeamName  = "#TeamA";
            const string secondTeamName = "#TeamB";

            MessageStore             messageStore  = new MessageStore();
            ICommandContext          context       = this.CreateCommandContext(messageStore, guildId: DefaultGuildId);
            GlobalTournamentsManager globalManager = new GlobalTournamentsManager();
            TournamentsManager       manager       = globalManager.GetOrAdd(DefaultGuildId, id => new TournamentsManager());

            HashSet <Team> teams = new HashSet <Team>()
            {
                new Team()
                {
                    Name = firstTeamName
                },
                new Team()
                {
                    Name = secondTeamName
                }
            };
            HashSet <Reader> readers = new HashSet <Reader>()
            {
                new Reader()
                {
                    Id   = 0,
                    Name = readerName
                }
            };
            RoundRobinScheduleFactory factory = new RoundRobinScheduleFactory(2, 0);
            Schedule schedule = factory.Generate(teams, readers);

            ITournamentState state = new TournamentState(DefaultGuildId, "T");

            state.Schedule = schedule;
            manager.AddOrUpdateTournament(state.Name, state, (name, oldState) => oldState);
            Assert.IsTrue(
                manager.TrySetCurrentTournament(state.Name, out string errorMessage),
                $"Failed to set the tournament: '{errorMessage}'");
            globalManager.GetOrAdd(DefaultGuildId, id => manager);

            BotCommandHandler commandHandler = new BotCommandHandler(context, globalManager);

            await commandHandler.GetScheduleAsync();

            Assert.AreEqual(1, messageStore.ChannelEmbeds.Count, "Unexpected number of embeds");

            string embed = messageStore.ChannelEmbeds[0];

            for (int round = 0; round < schedule.Rounds.Count; round++)
            {
                Assert.IsTrue(
                    embed.Contains(BotStrings.RoundNumber(round + 1)),
                    $"Round {round + 1} not found in embed. Embed: '{embed}'");
                string expectedGame = BotStrings.ScheduleLine(
                    readerName, schedule.Rounds[round].Games[0].Teams.Select(team => team.Name).ToArray());
                Assert.IsTrue(
                    embed.Contains(expectedGame),
                    $"Game '{expectedGame}' not foudn in embed. Embed: '{embed}'");
            }
        }
Ejemplo n.º 32
0
        ///// <summary>
        ///// Creates a new tournament following the specified parameters
        ///// </summary>
        //public async Task<bool> CreateTournament(string name, string url)
        //{
        //    //http://api.challonge.com/v1/documents/tournaments/create

        //    //Create RestClient & RestRequest
        //    RestClient restClient = new RestClient("https://api.challonge.com/v1/");
        //    RestRequest request = new RestRequest($"tournaments.json", Method.POST)
        //    {
        //        Credentials = new NetworkCredential(Username, APIKey),
        //        Parameters =
        //        {
        //            new Parameter
        //            {
        //                Name = "tournament[name]",
        //                Value = name,
        //                ContentType = null,
        //                Type = ParameterType.GetOrPost
        //            },
        //            new Parameter
        //            {
        //                Name = "tournament[url]",
        //                Value = url,
        //                ContentType = null,
        //                Type = ParameterType.GetOrPost
        //            }
        //        },
        //        RequestFormat = DataFormat.Json
        //    };

        //    //Pass request
        //    IRestResponse response = await restClient.ExecuteTaskAsync(request);
        //    if (response.StatusCode == HttpStatusCode.OK)
        //        return true;

        //    //Request failed
        //    return false;
        //}

        /// <summary>
        /// Retrieve list of tournaments falling under specified parameters
        /// </summary>
        public async Task <List <Bracket> > GetTournaments(string subDomain = null, TournamentState state = TournamentState.All, TournamentType type = TournamentType.All, DateTime createdAfter = default(DateTime), DateTime createdBefore = default(DateTime))
        {
            //http://api.challonge.com/v1/documents/tournaments/index

            //Create RestClient & RestRequest
            RestClient  restClient = new RestClient("https://api.challonge.com/v1/");
            RestRequest request    = new RestRequest($"tournaments.json", Method.GET)
            {
                Credentials = new NetworkCredential(Username, APIKey),
                Parameters  =
                {
                    new Parameter
                    {
                        Name        = "state",
                        Value       = Converters.TournamentStateConverter(state),
                        ContentType = null,
                        Type        = ParameterType.GetOrPost
                    },
                    new Parameter
                    {
                        Name        = "created_after",
                        Value       = createdAfter.ToString("yyyy-MM-dd"),
                        ContentType = null,
                        Type        = ParameterType.GetOrPost
                    },
                    new Parameter
                    {
                        Name        = "created_before",
                        Value       = !createdBefore.Equals(default(DateTime)) ? createdBefore.ToString("yyyy-MM-dd") : DateTime.Now.ToString("yyyy-MM-dd"),
                        ContentType = null,
                        Type        = ParameterType.GetOrPost
                    }
                },
                RequestFormat = DataFormat.Json
            };

            if (!string.IsNullOrWhiteSpace(Converters.TournamentTypeConverter(type)))
            {
                request.AddParameter("type", Converters.TournamentTypeConverter(type), null, ParameterType.GetOrPost);
            }
            if (!string.IsNullOrWhiteSpace(subDomain))
            {
                request.AddParameter("subdomain", subDomain, null, ParameterType.GetOrPost);
            }

            //Pass request
            IRestResponse response = await restClient.ExecuteTaskAsync(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                //Challonge API passed an error [Status Code 422]
                JToken content = JToken.Parse(response.Content);
                if (content.Type != JTokenType.Array && !Helpers.IsNullOrEmpty(content["errors"]))
                {
                    return(null);
                }

                List <Bracket> returnTournaments = new List <Bracket>();
                foreach (JToken tournament in content)
                {
                    returnTournaments.Add(tournament.First.First.ToObject <Bracket>());
                }

                return(returnTournaments);
            }

            //Request failed
            return(null);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// This is the master function for getting a game list.
        /// Used for searching for games.
        /// </summary>
        /// <param name="pn">the name of the player to get data of</param>
        public void GetTournaments(TournamentState state)
        {
            //Build request string
            string request = _url;

            //Pass request string to web accessor
            BeginFetchResult(request + "&status=" + (char)state);
        }