/// <summary> /// Получает результаты последней игры через API /// </summary> /// <returns>Результаты последней игры</returns> public async Task <GameResults> GetLastGameResults() { // URL для запроса string url = "http://poker.hamster56.ru/api/last-game"; // Токен для авторизации string token = "3xTHto57cOJLY0A1NUpOQs6j14Z49X8X"; // Результаты по-умолчанию GameResults results = new GameResults() { type = "-", places = new List <GamePlace>() }; // Заводим клиент для запроса HttpClient client = new HttpClient(); // Устанавливаем заголовок Accept client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Устанавливаем заголовок авторизации client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); // Запрашиваем данные HttpResponseMessage response = await client.GetAsync(url); // Если данные получены if (response.IsSuccessStatusCode) { // Заполняем результаты последней игры string content = response.Content.ReadAsStringAsync().Result; results = JsonConvert.DeserializeObject <GameResults>(content); } // Возвращаем результаты последней игры return(results); }
public async Task <GameResults> Launch(GameLaunchParams p) { Simulator.GameRunner runner = new Simulator.GameRunner(p.Practice, _sandboxPath); var result = await runner.Run(p.Teams.Select(t => _binaryDirectory + "/" + t.BinaryPath).ToList(), random.Next()); var ret = new GameResults(); ret.Points.AddRange(result.Scores); var memoryStream = new MemoryStream(); using (ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { var entry = archive.CreateEntry("record"); using (var entryStream = entry.Open()) { var bytes = result.ToByteArray(); entryStream.Write(bytes, 0, bytes.Length); } } var serialized = memoryStream.ToArray(); SHA256 sha = SHA256.Create(); var filename = ByteArrayToString(sha.ComputeHash(serialized)); var resultsFile = _recordsDirectory + "/" + filename; await File.WriteAllBytesAsync(resultsFile, serialized); new Mono.Unix.UnixFileInfo(resultsFile).FileAccessPermissions = Mono.Unix.FileAccessPermissions.UserRead | Mono.Unix.FileAccessPermissions.UserExecute; ret.ResultPath = filename; ret.NumTurns = result.Turns.Count; ret.NumStars.AddRange(result.NumStars); ret.CpuTime.AddRange(result.CpuTime); return(ret); }
private void RegisterRecord() { if (Opponent == "") { ShowDialog(Labels.WD_InsufficientRequiredParameters); return; } var gamePlayers = PlayersGameData.ToList(); gamePlayers.ForEach(x => x.GameId = GameId); var result = new GameData { GameId = GameId, TeamDivision = SelectedGrade, GameDate = GameDate, Place = Place, OpponentTeam = Opponent, Result = "", StartTime = StartTime, EndTime = EndTime, Summary = Summary, GameDetails = "", Half = "" }; GameResults.Add(result); }
public ActionResult Index() { GameResults results = ComputeScores(this.db); Dictionary <string, int> betCounts = GetBetCount(); ViewBag.GamesPlayedCount = results.GamesPlayedCount; if (HttpRuntime.Cache[CacheEnum.ConnectedPlayers] == null) { ViewBag.PlayersConnected = new List <string>(); } else { ViewBag.PlayersConnected = (List <string>)HttpRuntime.Cache[CacheEnum.ConnectedPlayers]; } return(View( db.Users.ToList <ApplicationUser>() .Select <ApplicationUser, UserModel>( i => new UserModel { Player = i.UserName, Score = (results.Results.ContainsKey(i.Id) ? results.Results[i.Id].Score : 0), GoodGuess = (results.Results.ContainsKey(i.Id) ? results.Results[i.Id].Count : 0), BetCount = (betCounts.ContainsKey(i.Id) ? betCounts[i.Id] : 0), TimeZoneInfoId = i.TimeZoneInfoId, Email = i.Email, Country = i.Country } ) .OrderByDescending <UserModel, decimal>(u => u.Score).ThenBy <UserModel, string>(i => i.Player).ToList())); }
/// <summary> /// Game play loop - continues until a winner is found /// </summary> /// <param name="player1">player 1</param> /// <param name="player2">player 2</param> /// <returns>GameResults object containing winning and losing player</returns> public GameResults PlayGame(Player player1, Player player2) { _battleOutput.OutputHeader(); int numberOfRounds = 0; while (player1.NumberOfCards != 0 && player2.NumberOfCards != 0) { Battle(player1, player2); numberOfRounds++; } GameResults results = new GameResults() { NumberOfRounds = numberOfRounds }; if (player2.NumberOfCards == 0) { results.WinningPlayer = player1; results.LosingPlayer = player2; Console.WriteLine($"Player 1 wins in {numberOfRounds} rounds!"); } else { results.WinningPlayer = player2; results.LosingPlayer = player1; Console.WriteLine($"Player 2 wins in {numberOfRounds} rounds!"); } return(results); }
public async Task <IHttpActionResult> PutGameResults(int id, GameResults gameResults) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != gameResults.ID) { return(BadRequest()); } db.Entry(gameResults).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GameResultsExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
private void Window_Closed(object sender, EventArgs e) { stopwatch.Stop(); double executionDuration = Math.Round(stopwatch.Elapsed.TotalMinutes, 2); if (destroyed == true) { GameResults result = new GameResults(PlayerName, GameResult.Lose, numberOfEnemies, executionDuration); gameResults.Add(result); } else if (winnedGame == true) { GameResults result = new GameResults(PlayerName, GameResult.Win, numberOfEnemies, executionDuration); gameResults.Add(result); } else if (winnedGame == false) { GameResults result = new GameResults(PlayerName, GameResult.InProgress, numberOfEnemies, executionDuration); gameResults.Add(result); } WriteGameResults(); this.Close(); }
public void Test_Game_PlayGame_TiePlayer2Wins() { List <Card> p1Cards = new List <Card> { new Card(CardSuit.DIAMOND, CardRank.RANK_JACK), new Card(CardSuit.CLUB, CardRank.RANK_KING), // Down card new Card(CardSuit.CLUB, CardRank.RANK_3) }; List <Card> p2Cards = new List <Card> { new Card(CardSuit.SPADE, CardRank.RANK_JACK), new Card(CardSuit.HEART, CardRank.RANK_6) }; Fake_PlayGame fp = new Fake_PlayGame(); Fake_PlayGame_Model fpm = fp.Setup(p1Cards, p2Cards); GameResults gameResults = fpm.Game.PlayGame(fpm.Player1, fpm.Player2); Assert.True(0 == fpm.Player1.NumberOfCards); Assert.True(0 < fpm.Player2.NumberOfCards); Assert.Equal <Player>(gameResults.LosingPlayer, fpm.Player1); Assert.Equal <Player>(gameResults.WinningPlayer, fpm.Player2); }
public void ThenTheViewModelGameRowsShouldBeCorrectForGameFilterId(int p0) { int gameFilterId = p0; var gs = GameSpreads .Where(_ => _.Game.GameFilterId == gameFilterId) .OrderBy(_ => _.GameId) .ToList(); Assert.AreEqual(gs.Count, actual.GameRows.Count, string.Format("GameRows.Count not equal for GameFilterId:{0}", gameFilterId)); int gameRowId = 0; foreach (var item in gs) { string expFavoriteTeam = item.FavoriteTeam.TeamLongName; string expUnderdogTeam = item.UnderdogTeam.TeamLongName; decimal expSpread = item.Spread; string expWinnerTeam = string.Empty; var gr = GameResults.FirstOrDefault(_ => _.GameSpreadId == item.GameSpreadId); if (gr == null) { expWinnerTeam = Teams.First(_ => _.TeamLongName == "No Winner").TeamLongName; } else { expWinnerTeam = gr.WinnerTeam.TeamLongName; } AssertResultsByGameGameRows(gameFilterId, gameRowId, expFavoriteTeam, expUnderdogTeam, expSpread, expWinnerTeam, actual.GameRows[gameRowId]); gameRowId++; } }
public void PlayEndSound(GameResults results) { if (results == GameResults.Win) audioSourceLib.WinLevel.Play (); else audioSourceLib.LoseLevel.Play (); }
public void SetGameResult(List <GameResult> gameResults) { var result = new GameResults(gameResults); var json = JsonUtility.ToJson(result); PlayerPrefs.SetString("GameResults", json); Debug.LogFormat("Game Result in Prefs: {0}", json); }
public void OnGameEnd(GameResults p_result) { m_gameEndPanelView.SetVisibility(true); m_gameEndPanelView.SetText(m_gameEndTexts[(int)p_result]); m_currentPlaying = m_gameEndSounds[(int)p_result]; m_currentPlaying.Play(); m_particles.SetActive(true); }
//----------------------------------------------------------------------------------- public void OnHighScore() { GameResults res = new GameResults(); res.score = m_player.glass.score; Game.instance.results = res; Game.instance.ui.SwitchToState(new PlayersScoreParams(/*m_player.glass.score*/)); }
private MinimaxResult MinimaxStep(BoardData p_board, Players p_player, int p_currentDepth) { GameResults t_gameResult = p_board.GetGameResult(); if (t_gameResult != GameResults.Unfinished) { int t_score = t_gameResult == GameResults.Win ? MAX_SCORE : -MAX_SCORE; return(new MinimaxResult(t_score, null)); } else if (p_currentDepth > MAX_DEPTH) { return(m_boardEvaluator.EvaluateBoard(p_board, p_player)); } Move t_bestMove = null; int t_bestScore = 0; if (p_board.CurrentPlayer == Players.Human) { t_bestScore = -INFINITE; } else { t_bestScore = INFINITE; } List <Move> t_moves = new List <Move>(); p_board.GetMoves(t_moves); foreach (Move t_move in t_moves) { BoardData t_newBoard = p_board.GetNewBoard(t_move); MinimaxResult t_result = MinimaxStep(t_newBoard, p_player, p_currentDepth + 1); if (p_board.CurrentPlayer == Players.Human) { if (t_bestScore < t_result.Score) { t_bestScore = t_result.Score; t_bestMove = t_move; } } else { if (t_result.Score < t_bestScore) { t_bestScore = t_result.Score; t_bestMove = t_move; } } } return(new MinimaxResult(t_bestScore, t_bestMove)); }
/// <summary> /// Exits the game /// </summary> private void EndLevel() { GameResults results = GameObject.Instantiate <GameObject>(ResultsPrefab).GetComponent <GameResults>(); foreach (PlayerScript player in playerScripts) { results.AddScore(player.name, player.Kills); } Application.LoadLevel("score"); }
public async Task <IHttpActionResult> GetGameResults(int id) { GameResults gameResults = await db.GameResults.FindAsync(id); if (gameResults == null) { return(NotFound()); } return(Ok(gameResults)); }
public async Task <IHttpActionResult> PostGameResults(GameResults gameResults) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.GameResults.Add(gameResults); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = gameResults.ID }, gameResults)); }
public static GameResults ComputeScores(ApplicationDbContext db) { if (HttpRuntime.Cache[CacheEnum.Scores] != null) { return((GameResults)HttpRuntime.Cache[CacheEnum.Scores]); } lock (_SyncRootScores) { Dictionary <string, UserResult> results = new Dictionary <string, UserResult>(); foreach (ApplicationUser user in db.Users) { results.Add(user.Id, new UserResult()); } var gamesPlayed = 0; foreach (Game game in db.Games.Where <Game>(g => g.Result.HasValue).ToList <Game>()) { gamesPlayed++; foreach (Bet bet in db.Bets.Where <Bet>(b => b.Game.ID == game.ID).ToList <Bet>()) { //we have a winner if (game.Result.Value == bet.Forecast) { decimal weight = 1; if (game.Phase.ID > 1 && game.Phase.ID < 5) { weight = 2; } if (game.Phase.ID == 5) { weight = 4; } results[bet.Owner.Id].Score += 10 * weight * game.GetOdd(game.Result.Value); results[bet.Owner.Id].Count += 1; } } } var data = new GameResults { GamesPlayedCount = gamesPlayed, Results = results }; HttpRuntime.Cache.Insert(CacheEnum.Scores, data, null, DateTime.UtcNow.AddMinutes(30), System.Web.Caching.Cache.NoSlidingExpiration); return(data); } }
//[InlineData(1000)] public void Test_Program_RunGameParallel(int numberOfRuns) { IBattleOutput battleOutput = new Fake_BattleOutput(); Parallel.For(0, numberOfRuns, i => { GameResults gameResults = Program.RunGame(battleOutput); Assert.True(gameResults.WinningPlayer.NumberOfCards == 52); Assert.True(gameResults.LosingPlayer.NumberOfCards == 0); Assert.True(gameResults.NumberOfRounds >= 1); }); }
public void Test_Program_RunGame(int numberOfRuns) { IBattleOutput battleOutput = new Fake_BattleOutput(); for (int i = 0; i < numberOfRuns; i++) { GameResults gameResults = Program.RunGame(battleOutput); Assert.True(gameResults.WinningPlayer.NumberOfCards == 52); Assert.True(gameResults.LosingPlayer.NumberOfCards == 0); Assert.True(gameResults.NumberOfRounds >= 1); // Pathological case: game ends in 1 round (many tie battles with eventual winner) } }
/// <summary> /// Запускает таймер /// </summary> private async void StartTimer() { // Если это первый запуск таймера if (firstStart) { // Надо загрузить блайнды GetBlinds(); } // Устанавливаем текст кнопки timerToggle.Content = "Остановить"; // Запускаем таймер timer.Start(); // Если первый запуск - нужно еще получить данные о последней игре if (firstStart) { // Показываем загрузку новой игры lastGame.Visibility = Visibility.Visible; // Заводим помощник для API ApiHelper helper = new ApiHelper(); // Получаем результаты последней игры GameResults results = await helper.GetLastGameResults(); // Устанавливаем тип игры lastGameType.Text = results.type; // Если запрос успешен (об этом говорит наличие мест) if (results.places.Count > 0) { // Перебираем места foreach (GamePlace place in results.places) { // Получаем текст string text = place.place + ". " + place.player; // Добавляем место AddPlace(text, HorizontalAlignment.Left); } } // Если запрос неудачен else { // Добавляем место AddPlace("-", HorizontalAlignment.Center); } // Прячем загрузку lastGameLoading.Visibility = Visibility.Collapsed; lastGameLoading.IsActive = false; // Показываем информацию о последней игре lastGameInfo.Visibility = Visibility.Visible; // Указываем что первый запуск произведен firstStart = false; } }
public void GivenTheDataIsLoadedForGameFilterId(int p0) { gameFilterId = p0; users = Users; var teams = Teams; gameSpreads = GameSpreads.Where(_ => _.Game.GameFilterId == gameFilterId).ToList(); gameResults = GameResults.Where(_ => _.GameSpread.Game.GameFilterId == gameFilterId).ToList(); userGameSelections = UserGameSelections.Where(_ => _.GameSpread.Game.GameFilterId == gameFilterId).ToList(); userGameResults = UserGameResults.Where(_ => _.UserGameSelection.GameSpread.Game.GameFilterId == gameFilterId).ToList(); noBetTeam = Teams.FirstOrDefault(_ => _.TeamLongName == "No Bet"); noPicksTeam = Teams.FirstOrDefault(_ => _.TeamLongName == "No Picks"); noWinnerTeam = Teams.FirstOrDefault(_ => _.TeamLongName == "No Winner"); }
public void UpdateValues(GameResults results) { if (results.WinningTeam == 0) { WinningTeamText.text = "Blue Team Wins!"; } else if (results.WinningTeam == 1) { WinningTeamText.text = "Red Team Wins!"; } ScoreText.text = string.Format("{0} guys left alive.", results.TeamScore); TimeText.text = string.Format("Game lasted {0:###.##} seconds.", results.GameTime); }
public async Task <IHttpActionResult> DeleteGameResults(int id) { GameResults gameResults = await db.GameResults.FindAsync(id); if (gameResults == null) { return(NotFound()); } db.GameResults.Remove(gameResults); await db.SaveChangesAsync(); return(Ok(gameResults)); }
/// <summary> /// Runs a game of trivia with the provided trivia source. /// Expected args: /// 1. Trivia source name that matches a provider in _questionProviders /// 2. (Optional) The number of rounds to play, default is 10 /// </summary> /// <param name="discordInterface"></param> /// <param name="args"></param> /// <param name="rawMessage"></param> protected override async Task Execute(IDiscordInterface discordInterface, string[] args, SocketMessage rawMessage) { if (!TryExtractArgs(args, out var questionProvider, out var gameLength)) { // Command was used wrong, print usage info and exit await discordInterface.SendMessageAsync(rawMessage.Channel, FullHelpText); return; } Subject <DiscordMessage> subject = new Subject <DiscordMessage>(); discordInterface.MessageReceived.ObserveOn(_scheduler) .Where(message => message.Channel.Id == rawMessage.Channel.Id) .Subscribe(message => { subject.OnNext(new DiscordMessage(message.Channel, message.Author.Username, message.Content)); }); var gameResult = new GameResults(); // Start asking questions var questions = await questionProvider.GetQuestions(gameLength); //TODO this might need to be async for (int i = 0; i < questions.Count; i++) { await discordInterface.SendMessageAsync(rawMessage.Channel, $"Question {i + 1}:\n{questions[i].Question}"); var result = await questions[i].ExecuteQuestion(subject.AsObservable(), questionProvider.QuestionDuration); if (result.Scores.Count == 0) { // No one was correct await discordInterface.SendMessageAsync(rawMessage.Channel, $"No one was correct! Answer:\n{questions[i].Answer}"); } else { gameResult.CombineWith(result); //Someone was correct await discordInterface.SendMessageAsync(rawMessage.Channel, $"{String.Join(", ", result.Scores.Where(score => score.Value > 0).Select(score => score.Key))} was correct!\n" + $"{gameResult.PrintScores()}"); } } // Game is over, inform everyone of the winner await discordInterface.SendMessageAsync(rawMessage.Channel, $"Game over, winner was {gameResult.GetWinner()}\n" + $"{gameResult.PrintScores()}"); }
public void Test_Game_PlayGame_Player2Wins(int numberOfCards) { List <Card> p1Cards = Enumerable.Repeat(new Card(CardSuit.SPADE, CardRank.RANK_6), numberOfCards).ToList(); List <Card> p2Cards = Enumerable.Repeat(new Card(CardSuit.SPADE, CardRank.RANK_10), numberOfCards).ToList(); Fake_PlayGame fp = new Fake_PlayGame(); Fake_PlayGame_Model fpm = fp.Setup(p1Cards, p2Cards); GameResults gameResults = fpm.Game.PlayGame(fpm.Player1, fpm.Player2); Assert.True(0 == fpm.Player1.NumberOfCards); Assert.True(numberOfCards * 2 == fpm.Player2.NumberOfCards); Assert.Equal <Player>(gameResults.LosingPlayer, fpm.Player1); Assert.Equal <Player>(gameResults.WinningPlayer, fpm.Player2); }
public void EndGame() { _isActive = false; int winningTeam = _teamCount[1] > _teamCount[0] ? 1 : 0; GameResults results = new GameResults { TeamScore = _teamCount[winningTeam], WinningTeam = winningTeam, GameTime = _gameTime }; GameEnded(results); }
// Use this for initialization void Start() { GameResults results = new GameResults(Player.Instance.Name, ScoreManager.Instance.Score); string serializedResults = JsonUtility.ToJson(results); byte[] body = Encoding.UTF8.GetBytes(serializedResults); Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("Content-Type", "application/json"); headers.Add("Content-Length", body.Length.ToString()); WWW request = new WWW("http://www.blokprty.com/api/gameresults", body, headers); StartCoroutine(OnGameResultsRequest(request)); }
private void MakeMove(Move p_move) { m_boardController.MakeMove(p_move); GameResults t_gameResult = m_boardController.GetBoard().GetGameResult(); if (t_gameResult != GameResults.Unfinished) { OnGameEnd(t_gameResult); } else { StartCoroutine(OnTurnFinished()); } }
//----------------------------------------------------------------------------------- public override void OnStart() { StatsProviderBase sp = Game.instance.stats; if (Game.instance.results == null) { m_nInputIndex = -1; var res = sp.GetCurStats(0, 10); for (int i = 0; i < res.Count; i++) { PlayersScoreItem item = m_scrollView.AddListItem <PlayersScoreItem>(); item.Set(res[i]); } } else { m_gameResults = Game.instance.results; //Clear results Game.instance.results = null; //Add new results m_nInputIndex = sp.GetNewScoreIndex(m_gameResults.score); //The results in high score if (m_nInputIndex >= 0) { var res = sp.GetCurStats(0, 10); for (int i = 0; i < res.Count + 1; i++) { var item = m_scrollView.AddListItem <PlayersScoreItem>(); int nElIdx = i < m_nInputIndex ? i : i - 1; if (i == m_nInputIndex) { var newRes = new StatsProviderBase.Stats(); newRes.m_nScore = m_gameResults.score; newRes.m_strPlayerName = "Enter Name"; item.SetAsInput(newRes); } else { item.Set(res[nElIdx]); } } } else { Game.instance.ui.SwitchToState(new MainMenuParams()); } } }
public void Show(GameResults results) { if (!results.won) { int secondsLeft = results.timeLeft; titleText.text = "You lost with " + secondsLeft + " second" + (secondsLeft == 1 ? "" : "s") + " left"; causeText.text = GetDeathMessage(results.deathReason); } else { titleText.text = "You won!"; causeText.text = ""; } // Aaaaand display gameObject.SetActive(true); }
private void PlayEndSequence(GameResults results) { if (results == GameResults.Win) endSequencer = Instantiate(winEndSequencerPrefab).GetComponent<SequencerManager>(); else endSequencer = Instantiate(loseEndSequencerPrefab).GetComponent<SequencerManager>(); Result = results; endSequencer.Play (); SoundManager.Instance.PlayEndSound (results); }
private void EndGame(GameResults result, bool isBlackjack = false) { RevealDealerFirstCard(); if (result == GameResults.Win) { if (isBlackjack) { Player1.Bankroll += Player1.CurrentBet * 3; // blackjack pays 2 to 1 lblGameResultOutput.Text = "Blackjack!"; } else { Player1.Bankroll += Player1.CurrentBet * 2; lblGameResultOutput.Text = "Win!"; } } else if (result == GameResults.Lose) { lblGameResultOutput.Text = "Lose!"; } else if (result == GameResults.Push) { lblGameResultOutput.Text = "Push!"; Player1.Bankroll += Player1.CurrentBet; } Player1.CurrentBet = 0; btnHit.Enabled = false; btnStand.Enabled = false; btnDoubleDown.Enabled = false; btnStartNewGame.Enabled = true; numBetAmount.Enabled = true; }