コード例 #1
0
 public void ShowGameSummary(GameSummary gameSummary)
 {
     using (var popup = new GameSummaryPopup(gameSummary))
     {
         popup.ShowDialog();
     }
 }
コード例 #2
0
        public async Task RefreshData()
        {
            summary = await GameDataService.GetGameSummary();

            FirstDay  = summary.CurrentDay - 1;
            standings = await StandingsService.GetStandings(1, summary.CurrentYear, 1);

            playoffs = await PlayoffService.GetPlayoffSummary(2, summary.CurrentYear);

            if (Yesterday != null)
            {
                await Yesterday.RefreshData();
            }
            if (Today != null)
            {
                await Today.RefreshData();
            }
            if (Tomorrow != null)
            {
                await Tomorrow.RefreshData();
            }


            StateHasChanged();
        }
コード例 #3
0
        public async Task <IActionResult> AddGameToUserCatalog(int gameId, int catalogId)
        {
            var userId = _userManager.GetUserId(User);
            var game   = await _context.Games.FindAsync(gameId);

            var catalog = await _context.Catalogs.FindAsync(catalogId);

            var rate    = _context.GameRates.Where(gr => gr.GameId == gameId && gr.AuthorId.Equals(userId)).FirstOrDefault()?.Rate;
            var summary = new GameSummary()
            {
                GameName     = game.Name,
                Game         = game,
                GameId       = game.Id,
                Rate         = rate,
                Genre        = game.Genre,
                GenreWrapper = game.Genre.GetAttribute <DisplayAttribute>().Name,
                UserId       = userId,
                Catalog      = catalog,
                CatalogId    = catalog.Id
            };
            await _context.GameSummaries.AddAsync(summary);

            await _context.SaveChangesAsync();

            return(RedirectToAction("Game", new { gameId = game.Id }));
        }
コード例 #4
0
ファイル: GameSummary.cs プロジェクト: Streus/Sketchtroid
    public static GameSummary Create(RectTransform parent, GameManager.Save data)
    {
        GameObject  pref    = ABU.LoadAsset <GameObject> ("core", "GameSummary");
        GameObject  inst    = Instantiate <GameObject> (pref, parent, false);
        GameSummary summary = inst.GetComponent <GameSummary> ();

        summary.SetName(data.gameName);
        summary.SetDifficulty(data.difficulty);
        summary.SetTime(data.gameTime);
        summary.SetArea(data.currScene);

        for (int i = 0; i < summary.damageTypes.Length; i++)
        {
            if ((data.dtUnlocks & (1 << (i + 1))) == 0)
            {
                summary.damageTypes [i].color = Color.clear;
            }
        }

        for (int i = 0; i < summary.abilities.Length; i++)
        {
            if ((data.abilities & (1 << i)) == 0)
            {
                summary.abilities [i].color = Color.clear;
            }
        }

        summary.data = data;

        return(summary);
    }
コード例 #5
0
        public async Task Handle(CreateGameSummaryCommand command)
        {
            GameSummary gameSummary = new GameSummary(command.Id, command.RetrosheetGameId, command.AwayTeam, command.HomeTeam,
                                                      command.UseDH, command.ParkCode, command.WinningPitcher, command.LosingPitcher, command.SavePitcher,
                                                      command.HasValidationErrors, command.GameDay, command.HomeTeamFinalScore, command.AwayTeamFinalScore, command.HomeTeamBatsFirst);
            await _session.Add(gameSummary);

            await _session.Commit();
        }
コード例 #6
0
        public GameSummary GetGameSummary()
        {
            GameSummary gameSummary = null;

            var xmlLoader = new XmlLoader();

            gameSummary = xmlLoader.GetXml <GameSummary>(GameSummaryXmlUrl);

            return(gameSummary);
        }
コード例 #7
0
 //add person on user's demand, if only it is valid
 public Person AddNewPerson(string name, GameSummary gameSummary)
 {
     using (var context = new PgContext())
     {
         //jezeli jest taka osoba juz, to nie dodawaj jej na pałę:
         if (context.Persons.Any(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)))
         {
             var person = context.Persons.Single(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
             gameSummary.GuessedGamePerson = new GamePerson()
             {
                 CorrectAnswers = -1,
                 Name           = person.Name,
                 OccurenceCount = person.Count,
                 PersonId       = person.PersonId
             };
             UpdateStructures(gameSummary);
             return(person);
         }
         // w pp. dodaj ją na pałę:
         context.Persons.Add(new Person()
         {
             Name  = name,
             Count = 0
         });
         context.SaveChanges();
         var personAdded = context.Persons.Single(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
         var questions   = context.Questions.ToList();
         foreach (var question in questions)
         {
             if (gameSummary.Entries.Any(x => x.QuestionId == question.QuestionId))
             {
                 var summaryQuestion = gameSummary.Entries.Single(x => x.QuestionId == question.QuestionId);
                 context.Answers.Add(new Answer()
                 {
                     NoCount    = summaryQuestion.UserAnswer == AnswerType.No ? 1 : 0,
                     YesCount   = summaryQuestion.UserAnswer == AnswerType.No ? 0 : 1,
                     PersonId   = personAdded.PersonId,
                     QuestionId = question.QuestionId
                 });
             }
             else
             {
                 context.Answers.Add(new Answer()
                 {
                     NoCount    = 0,
                     YesCount   = 0,
                     QuestionId = question.QuestionId,
                     PersonId   = personAdded.PersonId
                 });
             }
         }
         context.SaveChanges();
         return(personAdded);
     }
 }
コード例 #8
0
 //add new row in past games table (statistical purposes)
 public void SaveGameInfo(GameSummary data, bool won)
 {
     using (var context = new PgContext())
     {
         var newGame = new PastGame
         {
             QuestionsAsked = data.QuestionsAsked,
             Won            = won
         };
         context.PastGames.Add(newGame);
         context.SaveChanges();
     }
 }
コード例 #9
0
ファイル: DataModule.cs プロジェクト: bondyra/person-guesser
        //call updating maintenance and turn off the light
        public void EndGame()
        {
            if (_gameState != GameState.Finished && _gameState != GameState.Defeated)
            {
                return;
            }
            var summary = new GameSummary(_gameData, GuessedGamePerson);

            UpdatingModule.Instance.SaveGameInfo(summary, _gameState == GameState.Finished);
            if (_gameState == GameState.Finished)
            {
                UpdatingModule.Instance.UpdateStructures(summary);
            }
        }
コード例 #10
0
ファイル: GameController.cs プロジェクト: wpankratz/WiQuiz
        public IHttpActionResult GetGameList(string userId)
        {
            var model = new GameList();

            model.Games = new List <GameSummary>();

            var quizzes = quizDb.Quizzes.Where(x => x.IsPubslished).ToList();

            foreach (var quiz in quizzes)
            {
                var statisticsService = new GameStatisticsService(quiz.Id, userId);

                // TODO: Liste auswerten
                var gameModel = new GameSummary();

                gameModel.Name           = quiz.Name;
                gameModel.QuizId         = quiz.Id;
                gameModel.QuestionCount  = statisticsService.GetQuestions().Count;
                gameModel.MyGameCount    = statisticsService.GetMyGames().Count;        // wie oft habe ich gespielt
                gameModel.TotalGameCount = statisticsService.GetTotalGames().Count;

                var bestGame = statisticsService.GetBestGame();
                if (bestGame != null)
                {
                    gameModel.BestGame = new GameApproach
                    {
                        PlayDateTime = bestGame.Game.CreatedAt,
                        Rank         = 0,
                        Score        = bestGame.CorrectAnswerCount
                    };
                }

                var lastGame = statisticsService.GetLastGame();
                if (lastGame != null)
                {
                    gameModel.LastGame = new GameApproach
                    {
                        PlayDateTime = lastGame.Game.CreatedAt,
                        Rank         = 0,
                        Score        = lastGame.CorrectAnswerCount
                    };
                }

                model.Games.Add(gameModel);
            }



            return(Ok(model));
        }
コード例 #11
0
ファイル: Configuration.cs プロジェクト: sycomix/BotWars
        protected override void Seed(ApplicationDbContext context)
        {
            string defaultOwnerId = null;
            var    defaultOwner   = context.Users.FirstOrDefault();

            if (defaultOwner != null)
            {
                defaultOwnerId = defaultOwner.Id;
            }

            var divideByZero = UpsertPlayerBot(new PlayerBot()
            {
                Id      = -1,
                Name    = "Berserkerbot",
                OwnerId = defaultOwnerId,
                URL     = "http://berserkerbot.azurewebsites.net/api/bot",
            }, context);

            var grahamBot = UpsertPlayerBot(new PlayerBot()
            {
                Id      = -1,
                Name    = "RandomBot",
                OwnerId = defaultOwnerId,
                URL     = "http://randombot.azurewebsites.net/api/bot",
            }, context);


            if (!context.GameSummaries.Any())
            {
                var match = new GameSummary()
                {
                    Player1        = grahamBot,
                    Player2        = divideByZero,
                    TournamentGame = false,
                    Winner         = divideByZero
                };
                context.GameSummaries.Add(match);
            }

            var unownedBots = context.PlayerBots.Where(x => x.Owner == null);

            foreach (var b in unownedBots)
            {
                b.OwnerId = defaultOwnerId;
            }

            context.SaveChanges();
            base.Seed(context);
        }
コード例 #12
0
        public GameSummaryPopup(GameSummary gameSummary)
        {
            _gameSummary = gameSummary;
            InitializeComponent();

            _statsPanel = new TableLayoutPanel();
            LayoutPanel.Controls.Add(_statsPanel, 0, 1);

            _statsPanel.TabIndex    = 2;
            _statsPanel.ColumnCount = 2;
            _statsPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
            _statsPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
            _statsPanel.Dock = DockStyle.Fill;
            _statsPanel.Name = "StatsPanel";
        }
コード例 #13
0
        protected override void OnInitialized()
        {
            GameData = GameDataService.GetGameSummary().Result;
            var seasons = CompetitionService.GetCompetitionsByYear(GameData.CurrentYear).Result.Where(c => c.Type == CompetitionViewModel.SEASON_TYPE).ToList();

            if (seasons.Count > 0)
            {
                StandingsModel = StandingsService.GetStandings(seasons[0].Id, 1).Result;
            }
            else
            {
                StandingsModel = null;
            }

            DropDownState.OnChange += StateHasChanged;
        }
コード例 #14
0
        public async Task <IActionResult> ImportSummaries(IFormFile jsonfile, string userId = null)
        {
            userId ??= _userManager.GetUserId(User);
            if (jsonfile != null)
            {
                byte[] jsonBytes = null;
                using (var reader = new BinaryReader(jsonfile.OpenReadStream()))
                {
                    jsonBytes = reader.ReadBytes((int)jsonfile.Length);
                }
                var json       = Encoding.UTF8.GetString(jsonBytes);
                var gs         = JsonConvert.DeserializeObject <List <GameSummaryDTO> >(json);
                var existingGS = _dbContext.GetGameSummaries(userId);
                foreach (var gameSummaryDTO in gs.Where(gs => !existingGS.Any(egs => egs.GameId.Equals(gs.GameId))))
                {
                    var gameSummary = new GameSummary();
                    var game        = await _dbContext.Games.FindAsync(gameSummaryDTO.GameId);

                    gameSummary.GameName = game.Name;
                    gameSummary.Game     = game;
                    gameSummary.GameId   = game.Id;
                    gameSummary.Rate     = gameSummaryDTO.Rate;
                    if (gameSummaryDTO.Rate.HasValue)
                    {
                        var gameRate = new GameRate()
                        {
                            AuthorId = userId,
                            GameId   = game.Id,
                            Rate     = gameSummaryDTO.Rate.Value
                        };
                        await _dbContext.GameRates.AddAsync(gameRate);
                    }
                    gameSummary.Genre        = game.Genre;
                    gameSummary.GenreWrapper = game.Genre.GetAttribute <DisplayAttribute>().Name;
                    gameSummary.UserId       = userId;
                    var catalog = await _dbContext.Catalogs.FindAsync(gameSummaryDTO.CatalogId);

                    gameSummary.Catalog   = catalog;
                    gameSummary.CatalogId = catalog.Id;
                    await _dbContext.GameSummaries.AddAsync(gameSummary);
                }

                await _dbContext.SaveChangesAsync();
            }
            return(RedirectToAction("Profile"));
        }
コード例 #15
0
        private async Task StartAsync()
        {
            try
            {
                while (true)
                {
                    var gameArgs = await GameSummary.GetGameArgsAsync();

                    await SnakeMasterViewModel.GoSnakeAsync(gameArgs);

                    SnakeMasterViewModel.Reset();
                }
            }
            catch (Exception)
            {
                // TODO
            }
        }
コード例 #16
0
        public async Task <Guid> AddGame(GameSummary gameSummary, GameOrigin origin, int seasonId)
        {
            var dbGame = new DbGame();

            dbGame.Errors       = gameSummary.Errors;
            dbGame.InitDuration = gameSummary.InitDuration;
            dbGame.GameDuration = gameSummary.GameDuration;
            dbGame.Stdout       = gameSummary.StandardOutput;
            dbGame.Stderr       = gameSummary.StandardError;
            dbGame.Origin       = origin;
            dbGame.SeasonId     = seasonId;

            this._dbContext.Games.Add(dbGame);

            foreach (var(_, playerSummary) in gameSummary.Players)
            {
                var userDbId = playerSummary.WebsiteId !.Value;
                var botDbId  = playerSummary.BotId !.Value;

                var dbGameUser = new DbGameUser
                {
                    Game        = dbGame,
                    UserId      = userDbId,
                    Score       = playerSummary.Score,
                    DeltaPoints = playerSummary.DeltaPoints ?? 0,
                    Rank        = playerSummary.Rank,
                    Errors      = playerSummary.Errors,
                    BotId       = botDbId
                };

                this._dbContext.GameUsers.Add(dbGameUser);

                if (playerSummary.Points.HasValue && playerSummary.Points.Value > 0)
                {
                    var dbUser = await this._dbContext.Users.SingleAsync(u => u.Id == userDbId).ConfigureAwait(false);

                    dbUser.Points = playerSummary.Points.Value;
                }
            }

            await this._dbContext.SaveChangesAsync().ConfigureAwait(false);

            return(dbGame.Id);
        }
コード例 #17
0
        public SummaryData(GameSummary summary)
        {
            GuessedName = summary.GuessedGamePerson.Name;

            var entryList = new List <EntryData>();

            foreach (var entry in summary?.Entries)
            {
                var systemAnswer = entry.SystemAnswer.ToString().Split('.').Last();
                var userAnswer   = entry.UserAnswer.ToString().Split('.').Last();
                entryList.Add(new EntryData()
                {
                    QuestionText = entry.QuestionText,
                    SystemAnswer = systemAnswer == "Yes" ? "Tak" : systemAnswer == "No" ? "Nie" : "Nieznane",
                    UserAnswer   = userAnswer == "Yes" ? "Tak" : userAnswer == "No" ? "Nie" : "Nieznane",
                });
            }
            Entries = entryList.ToArray();
        }
コード例 #18
0
        public async Task <GameSummary> GetSummary(Guid player)
        {
            var tasks       = this.Players.Select(p => this.GrainFactory.GetGrain <IPlayerGrain>(p).GetUsername()).ToArray();
            var playerNames = await Task.WhenAll(tasks);

            var summary = new GameSummary()
            {
                GameId      = this.GrainReference.GetPrimaryKey(),
                Name        = this.Name,
                GameStarter = this.State == GameState.InPlay,
                NumPlayers  = this.Players.Count,
                Usernames   = playerNames,
                State       = this.State,
                NumMoves    = 0,
                YourMove    = false,
                Outcome     = GameOutcome.Draw,
            };

            return(summary);
        }
コード例 #19
0
ファイル: BattleController.cs プロジェクト: sycomix/BotWars
        private void SaveGameResult(int bot1Id, int bot2Id, Game game)
        {
            var p1 = _db.PlayerBots.First(x => x.Id == bot1Id);
            var p2 = _db.PlayerBots.First(x => x.Id == bot2Id);

            if (String.IsNullOrWhiteSpace(game.GameState.Winner))
            {
                //If the game progressed to the turn limit, the winner won't be set yet, so we do it here.
                SetWinnerByBotCount(game);
            }
            var gameResult = new GameSummary()
            {
                Player1        = p1,
                Player2        = p2,
                TournamentGame = false,
                Winner         = game.GameState.Winner == "p1" ? p1 : game.GameState.Winner == "p2" ? p2 : null
            };

            _db.GameSummaries.Add(gameResult);
            _db.SaveChanges();
        }
コード例 #20
0
        //happens in the end of a game - get information about past game
        public void UpdateStructures(GameSummary data)
        {
            using (var context = new PgContext())
            {
                context.Persons.Single(x => x.Name == data.GuessedGamePerson.Name).Count++;
                context.SaveChanges();
                foreach (var question in data.Entries)
                {
                    var dbQuestion = context.Questions.Single(x => x.Text == question.QuestionText);
                    var answer     = context.Answers.Single(x => x.QuestionId == dbQuestion.QuestionId &&
                                                            x.PersonId == data.GuessedGamePerson.PersonId);
                    answer.NoCount = question.UserAnswer == AnswerType.No
                        ? answer.NoCount + 1
                        : answer.NoCount;

                    answer.YesCount = question.UserAnswer == AnswerType.Yes
                        ? answer.YesCount + 1
                        : answer.YesCount;
                    context.SaveChanges();
                }
            }
        }
コード例 #21
0
    private void modifyList(bool building)
    {
        //clear the list
        for (int i = 0; i < transform.childCount; i++)
        {
            Destroy(transform.GetChild(i).gameObject);
        }

        //done if leaving the menu
        if (!building)
        {
            return;
        }

        if (Directory.Exists(GameManager.savePath))
        {
            string[] saves = Directory.GetFiles(GameManager.savePath);
            foreach (string save in saves)
            {
                int    start     = save.LastIndexOf(Path.DirectorySeparatorChar) + 1;
                int    end       = save.LastIndexOf('.');
                string sani_save = save.Substring(start, end - start);
                GameSummary.Create(GetComponent <RectTransform> (), GameManager.instance.loadSave(sani_save));
                Debug.Log("Loaded " + sani_save);                  //DEBUG
            }
        }
        else
        {
            //TODO display special graphic for no saves
        }

        // orient the window on the first save, ifex
        targetChild = 0;
        if (transform.childCount > 0)
        {
            calcTargetX();
        }
    }
コード例 #22
0
        public Task <GameSummary> GetGameSummary()
        {
            var data         = gameDataRepo.GetCurrentData();
            var competitions = competitionService.GetCompetitionsByYear(data.CurrentYear).Result;
            var configs      = competitionConfigRepo.GetConfigByYear(data.CurrentYear).ToList();

            var summary = new GameSummary()
            {
                CurrentDay  = data.CurrentDay,
                CurrentYear = data.CurrentYear,
                CompetitionForCurrentYear = competitions
            };

            bool allowIncrementYear        = IsYearComplete(data.CurrentYear);
            bool allowStartNextCompetition = false;

            //check if any competition is ready to start
            configs.ForEach(c =>
            {
                if (IsCompetitionReadyToStart(c, data.CurrentYear))
                {
                    allowStartNextCompetition = true;
                }
            });
            //first check is if we have an active competition, then disable if a competition needs to start
            bool allowPlayGames = competitions.Where(c => c.Started && !c.Complete).FirstOrDefault() != null && !allowStartNextCompetition;

            summary.AllowIncrementYear        = allowIncrementYear;
            summary.AllowPlayGames            = allowPlayGames;
            summary.AllowStartNextCompetition = allowStartNextCompetition;

            for (int i = 1; i <= summary.CurrentYear; i++)
            {
                summary.Years.Add(i);
            }

            return(Task.FromResult(summary));
        }
コード例 #23
0
        public async Task <IActionResult> Create([FromBody] GameSummary request)
        {
            var id = await m_gameService.CreateGame(request.Players, request.Name);

            return(Created(Url.RouteUrl("GetGame", new { id }), null));
        }
コード例 #24
0
ファイル: HeartPiece.cs プロジェクト: mgartz/skwer_unity
	// Use this for initialization
	void Start () {
		originalPosition = transform.localPosition;
		isAppearing = false;
		shouldSummaryShowArray = false;
		gameSummary = GameObject.Find("GameSummary").GetComponent<GameSummary>();
	}
コード例 #25
0
 public Task <Guid> AddGame(GameSummary gameSummary, GameOrigin origin, int seasonId)
 {
     this._objectCache.Remove(GetRankedUsersKeyFormat);
     return(this._underlyingRepository.AddGame(gameSummary, origin, seasonId));
 }
        public IActionResult Index(NewGameApiRequest novoJogador)
        {
            if (ModelState.IsValid)
            {
                //Novo Jogo
                HttpClient          client   = MyHTTPClientNewGame.Client;
                string              path     = "/api/NewGame";
                HttpResponseMessage response = client.PostAsJsonAsync(path, novoJogador).Result;
                if (!response.IsSuccessStatusCode)
                {
                    return(View("Index"));
                }

                PlayApiResponse nr = response.Content.ReadAsAsync <PlayApiResponse>().Result;



                int rd = 0;
                if (nr.PlayerName == "auto1")
                {
                    rd = 1;
                }
                else if (nr.PlayerName == "auto3")
                {
                    rd = 3;
                }
                else if (nr.PlayerName == "auto10")
                {
                    rd = 10;
                }
                else if (nr.PlayerName == "auto0")
                {
                    rd = 100;
                }

                Repository.ClearRounds();



                // Ciclo de rondas
                while (nr.RoundCount < rd && nr.PlayerCredits >= 10)
                {
                    RoundSummary rs = new RoundSummary();
                    rs.Blackjack = false;

                    int initialBet = 0;
                    if (nr.PlayerCredits > 200)
                    {
                        initialBet = 50;
                    }
                    else if (nr.PlayerCredits > 100)
                    {
                        initialBet = 25;
                    }
                    else
                    {
                        initialBet = 10;
                    }

                    rs.InitialCredits = nr.PlayerCredits;

                    PlayApiRequest rq = new PlayApiRequest(nr.GameId, (int)PlayerAction.NewRound, initialBet);
                    response = client.PostAsJsonAsync("/api/Play", rq).Result;
                    if (!response.IsSuccessStatusCode)
                    {
                        return(View("Index"));
                    }

                    nr = response.Content.ReadAsAsync <PlayApiResponse>().Result;

                    rs.Rounds = nr.RoundCount + 1;

                    if (nr.RoundFinalResult == (int)RoundFinalResult.BlackJack)
                    {
                        rs.Blackjack = true;
                    }


                    //Jogadas
                    while (nr.PlayingRound == true && nr.PlayerCredits >= 10)
                    {
                        PlayerAction playerAction;

                        CardMethods card = new CardMethods();

                        int playerHand = card.ValueHands(nr.PlayerHand);
                        int dealerHand = card.ValueHands(nr.Dealerhand);

                        //if (card.ValueHands(nr.PlayerHand) >= 5 && card.ValueHands(nr.PlayerHand) <= 10)
                        //{
                        //    playerAction = PlayerAction.Double;
                        //    rs.Double = true;
                        //    rs.Bet = rs.Bet + rs.Bet;
                        //}
                        //else if (card.ValueHands(nr.PlayerHand) < 5 && card.ValueHands(nr.Dealerhand) == 11)
                        //    playerAction = PlayerAction.Surrender;
                        //else if (card.ValueHands(nr.PlayerHand) <= 16)
                        //    playerAction = PlayerAction.Hit;
                        //else if (card.ValueHands(nr.PlayerHand) >= 17)
                        //    playerAction = PlayerAction.Stand;
                        //else
                        //    playerAction = PlayerAction.Surrender;

                        if (dealerHand >= 9 && playerHand == 16)
                        {
                            playerAction = PlayerAction.Surrender;
                        }
                        else if (dealerHand == 10 && playerHand == 15)
                        {
                            playerAction = PlayerAction.Surrender;
                        }
                        else if (playerHand >= 17 && playerHand <= 21)
                        {
                            playerAction = PlayerAction.Stand;
                        }
                        else if (playerHand == 16 && dealerHand >= 7 && dealerHand <= 8)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand == 16 && dealerHand >= 2 && dealerHand <= 6)
                        {
                            playerAction = PlayerAction.Stand;
                        }
                        else if (playerHand == 15 && dealerHand == 11)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand == 15 && dealerHand >= 7 && dealerHand <= 9)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand == 15 && dealerHand >= 2 && dealerHand <= 6)
                        {
                            playerAction = PlayerAction.Stand;
                        }
                        else if (playerHand >= 12 && playerHand <= 14 && dealerHand >= 7)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand >= 13 && playerHand <= 14 && dealerHand >= 2 && dealerHand <= 6)
                        {
                            playerAction = PlayerAction.Stand;
                        }
                        else if (playerHand == 12 && dealerHand >= 4 && dealerHand <= 6)
                        {
                            playerAction = PlayerAction.Stand;
                        }
                        else if (playerHand == 12 && dealerHand >= 2 && dealerHand <= 3)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand == 11 && dealerHand == 11)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand == 11)
                        {
                            if (nr.PlayerCredits >= 10)
                            {
                                playerAction = PlayerAction.Double;
                                rs.Double    = true;
                                rs.Bet       = rs.Bet + rs.Bet;
                            }
                            else
                            {
                                playerAction = PlayerAction.Hit;
                            }
                        }
                        else if (playerHand == 10 && dealerHand >= 10)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand == 10)
                        {
                            if (nr.PlayerCredits >= 10)
                            {
                                playerAction = PlayerAction.Double;
                                rs.Double    = true;
                                rs.Bet       = rs.Bet + rs.Bet;
                            }
                            else
                            {
                                playerAction = PlayerAction.Hit;
                            }
                        }
                        else if (playerHand == 9 && dealerHand >= 7)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else if (playerHand == 9 && dealerHand >= 3)
                        {
                            if (nr.PlayerCredits >= 10)
                            {
                                playerAction = PlayerAction.Double;
                                rs.Double    = true;
                                rs.Bet       = rs.Bet + rs.Bet;
                            }
                            else
                            {
                                playerAction = PlayerAction.Hit;
                            }
                        }
                        else if (playerHand == 9)
                        {
                            playerAction = PlayerAction.Hit;
                        }
                        else
                        {
                            playerAction = PlayerAction.Hit;
                        }

                        PlayApiRequest req = new PlayApiRequest(nr.GameId, (int)playerAction, initialBet);
                        response = client.PostAsJsonAsync("/api/Play", req).Result;
                        if (!response.IsSuccessStatusCode)
                        {
                            return(View("Index"));
                        }

                        nr = response.Content.ReadAsAsync <PlayApiResponse>().Result;

                        if (playerAction == PlayerAction.Double)
                        {
                            rs.Bet = rs.Bet + rs.Bet;
                        }
                        else
                        {
                            rs.Bet = initialBet;
                        }

                        if (card.ValueHands(nr.Dealerhand) == 21 && nr.Dealerhand.Count == 2)
                        {
                            rs.DealerBlackjack = true;
                        }
                        else
                        {
                            rs.DealerBlackjack = false;
                        }
                    }

                    rs.RoundResult  = nr.RoundFinalResult;
                    rs.FinalCredits = nr.PlayerCredits;
                    Repository.AddRound(rs);
                }

                path = "/api/Play/rGAUUmCfk3vUgfSF/" + nr.GameId;
                HttpResponseMessage resp = client.GetAsync(path).Result;
                if (!resp.IsSuccessStatusCode)
                {
                    return(View("Index"));
                }
                nr = resp.Content.ReadAsAsync <PlayApiResponse>().Result;

                path = "/api/Quit";
                QuitApiRequest reqq = new QuitApiRequest(nr.GameId);
                response = client.PostAsJsonAsync(path, reqq).Result;
                if (!response.IsSuccessStatusCode)
                {
                    return(View("Index"));
                }

                List <RoundSummary> rounds = Repository.Rounds;

                GameSummary g = new GameSummary();
                g.Rounds  = nr.RoundCount;
                g.Credits = nr.PlayerCredits;
                foreach (RoundSummary r in rounds)
                {
                    g.AvgBet = r.Bet + g.AvgBet;
                    if (r.Bet > g.MaxBet)
                    {
                        g.MaxBet = r.Bet;
                    }
                    if (r.Bet < g.MinBet)
                    {
                        g.MinBet = r.Bet;
                    }
                    else
                    {
                        g.MinBet = 10;
                    }
                    if (r.RoundResult == (int)RoundResult.BlackJack)
                    {
                        g.PlayerBlackjack = g.PlayerBlackjack + 1;
                    }
                    if (r.DealerBlackjack == true)
                    {
                        g.DealerBlackjack = g.DealerBlackjack + 1;
                    }
                }
                g.AvgBet = g.AvgBet / rounds.Count();

                ViewBag.Game = g;

                return(View("Result", rounds));
            }
            else
            {
                return(View());
            }
        }
コード例 #27
0
 private void UpdateSummary()
 {
     Summary = new GameSummary(name, engine.Model);
     SummaryUpdated?.Invoke();
 }
コード例 #28
0
 public void GettingSummaryOfEstimatingRoom(Room room, List <ProjectTask> tasks, List <RoomParticipant> participants, List <User> users, ProjectTasksController projectTasksController, GameSummary summary, RoomsController roomsController)
 {
     "Given a list of users"
     .x(() =>
     {
         users = new List <User>()
         {
             new User()
             {
                 id = 1, username = "******", mailAddress = "*****@*****.**"
             },
             new User()
             {
                 id = 2, username = "******", mailAddress = "*****@*****.**"
             },
             new User()
             {
                 id = 3, username = "******", mailAddress = "*****@*****.**"
             },
             new User()
             {
                 id = 4, username = "******", mailAddress = "*****@*****.**"
             },
         };
         _context.User.AddRange(users);
         _context.SaveChanges();
     });
     "And a room"
     .x(() =>
     {
         room = new Room()
         {
             hostMailAddress = users[3].mailAddress, id = 2999, name = "BDD Testing Room"
         };
         _context.Room.Add(room);
         _context.SaveChanges();
     });
     "And list of tasks"
     .x(() =>
     {
         tasks = new List <ProjectTask>()
         {
             new ProjectTask()
             {
                 id = 1, title = "Add a new task", RoomId = 2999, estimate = 0, status = TaskStatus.UNESTIMATED.name, author = users[3]
             },
             new ProjectTask()
             {
                 id = 2, title = "Assign estimates", RoomId = 2999, estimate = 0, status = TaskStatus.UNESTIMATED.name, author = users[3]
             },
             new ProjectTask()
             {
                 id = 3, title = "Sign in to an application", RoomId = 2999, estimate = 0, status = TaskStatus.UNESTIMATED.name, author = users[3]
             },
             new ProjectTask()
             {
                 id = 4, title = "Sign up to an application", RoomId = 2999, estimate = 0, status = TaskStatus.UNESTIMATED.name, author = users[3]
             }
         };
         _context.ProjectTask.AddRange(tasks);
         _context.SaveChanges();
         tasks.ForEach(t => _context.Entry(t).State = EntityState.Detached);
     });
     "And having users assigned to the room"
     .x(() =>
     {
         participants = new List <RoomParticipant>();
         users.ForEach(u =>
         {
             if (u.id != 4)
             {
                 participants.Add(new RoomParticipant()
                 {
                     mailAddress = u.mailAddress, roomId = 2999
                 });
             }
         });
         _context.RoomParticipant.AddRange(participants);
         _context.SaveChanges();
     });
     "When I estimate all tasks"
     .x(async() =>
     {
         projectTasksController = new ProjectTasksController(_context);
         await projectTasksController.PatchProjectTaskEstimate(1, 1);
         await projectTasksController.PatchProjectTaskEstimate(2, 10);
         await projectTasksController.PatchProjectTaskEstimate(3, 5);
         await projectTasksController.PatchProjectTaskEstimate(4, 20);
     });
     "And request room summary"
     .x(async() =>
     {
         roomsController = new RoomsController(_context);
         summary         = await roomsController.GetGameSummary(2999);
     });
     "Then all tasks will be present"
     .x(() =>
     {
         tasks = _context.ProjectTask.Where(pt => pt.RoomId == 2999).ToList();
         tasks.ForEach(t =>
         {
             Assert.Contains(summary.tasks, (pt) => t.id == pt.id);
         });
     });
     "And all tasks will be having correct estimates"
     .x(() =>
     {
         tasks.ForEach(t =>
         {
             Assert.Contains(summary.tasks, (pt) => t.id == pt.id && t.estimate == pt.estimate);
         });
     });
     "And all participants will be present"
     .x(() =>
     {
         users.ForEach(u =>
         {
             if (u.mailAddress != summary.host)
             {
                 Assert.Contains(summary.participants, rp => rp.id == u.id);
             }
         });
     });
 }