public int CalculateELO(int playerOneRating, int playerTwoRating, GameOutcome outcome) { //viktning int eloK = 32; return((int)(eloK * ((int)outcome - ExpectationToWin(playerOneRating, playerTwoRating)))); }
public SpinOutcome(GameOutcome outcome) : this(outcome.Name, outcome.Command) { this.Payout = Convert.ToInt32(outcome.Payout * 100.0); this.UserChance = outcome.RoleProbabilities[UserRoleEnum.User]; this.SubscriberChance = outcome.RoleProbabilities[UserRoleEnum.Subscriber]; this.ModChance = outcome.RoleProbabilities[UserRoleEnum.Mod]; }
// vart vill spelare lägga sin mark public static void Main() { var markSpot = new Markspot(); var updateBoard = new UpdateBoard(); var gameOutcome = new GameOutcome(); while (winner != 1) { winner = gameOutcome.IsItWin(); updateBoard.UpdatingBoard(); markSpot.PlaceMark(); // Places the player mark (X or O) on the spot they choose gameOutcome.IsItWin(); howManyTurnsPlayed++; if (howManyTurnsPlayed == 9 && winner != 1) { gameOutcome.Draw(); winner = 0; } } // showBoard.Board(); // show boards // playing.whicePlayerToPlay(); // What player turn is it // markSpot.placeMark(); // Places the player mark (X or O) on the spot they choose //choice }
public async Task <ActionResult <RoundWithBotResult> > Post([FromHeader(Name = "X-AuthToken"), Required] string userToken, [FromBody] string userFigureRaw, [FromServices] IStorage <string> tokens) { _logger.LogInformation($"{nameof(BotGameController)}: Round with bot requested"); var userId = (await tokens.GetAllAsync()) .Where(tk => tk.Item == userToken) .Select(tk => tk.Id) .FirstOrDefault(); if (userId > 0) //if user was found { bool isCorrectFigure = Enum.TryParse <MoveOptions>(userFigureRaw, true, out MoveOptions userFigure); if (isCorrectFigure == false) { return(BadRequest("Invalid move option")); } MoveOptions botMoveOption = _botGameService.MakeRandomChoice(); GameOutcome roundResult = _gameService.GetGameResult(userFigure, botMoveOption); _logger.LogInformation($"{nameof(BotGameController)}: Round with bot ended"); RoundWithBotResult result = new RoundWithBotResult() { UserMoveOption = userFigure, BotMoveOption = botMoveOption, RoundResult = roundResult.ToString() }; var jsonResult = JsonSerializer.Serialize(result); return(Ok(jsonResult)); } return(StatusCode((int)HttpStatusCode.Forbidden, "Unauthorized access")); }
private void AddGameToTeamStats(List <Player> players, bool isTerroristTeam, GameOutcome outcome, List <TeamStats> teams) { if (players.Count == 0) { return; } var team = teams.FirstOrDefault(teamStats => IsSameTeam(teamStats.Players, players)); if (team == null) { var playerInfos = players.Select(player => GetPlayerInfo(player)); playerInfos = playerInfos.OrderBy(player => player.Name); team = new TeamStats(playerInfos.ToList()); teams.Add(team); } if (outcome == GameOutcome.Draw) { team.Draws++; } else if ( isTerroristTeam && outcome == GameOutcome.TerroristsWin || !isTerroristTeam && outcome == GameOutcome.CounterTerroristsWin ) { team.Wins++; } else { team.Losses++; } }
public void SendGameOutcome() { var manager = FindObjectOfType <AMainManager>(); List <messages.Player> leaderboards = manager.PlayersInstances .Select(x => x.Value) .OrderByDescending(x => x.CompletedPotionCount) .ThenByDescending(x => x.CollectedIngredientCount) .Select(x => new messages.Player() { color = ColorUtility.ToHtmlStringRGBA(ColorsManager.Get().PlayerAppColors[x.ID]), id = x.ID, name = x.Name, ingredients = x.CollectedIngredientCount, potions = x.CompletedPotionCount, }).ToList(); var gameOutcome = new GameOutcome() { leaderboards = leaderboards.ToArray(), }; var serialized = JsonConvert.SerializeObject(gameOutcome); _Socket.Emit(Command.GAME_OUTCOME, new JSONObject(serialized)); }
/// <summary> /// Choose the best for the 2nd /// </summary> public static GameOutcome BestForSecond(this GameOutcome left, GameOutcome right) { if (left == right) { return(left); } if (left == GameOutcome.SecondWin) { return(left); } else if (right == GameOutcome.SecondWin) { return(right); } else if (left == GameOutcome.Draw) { return(left); } else if (right == GameOutcome.Draw) { return(right); } else if (left == GameOutcome.None) { return(left); } else if (right == GameOutcome.None) { return(right); } return(left); }
public void CommandButtonCreateExecuteTest004_CheckIfESLFileVersionAdded() { Mock <ITrackerFactory> trackerFactory = new Mock <ITrackerFactory>(); Mock <IMessenger> messanger = new Mock <IMessenger>(); trackerFactory.Setup(tf => tf.GetService <IMessenger>()).Returns(messanger.Object); Mock <ISettings> settings = new Mock <ISettings>(); trackerFactory.Setup(tf => tf.GetService <ISettings>()).Returns(settings.Object); Mock <ITracker> tracker = new Mock <ITracker>(); tracker.Setup(t => t.Games).Returns(new ObservableCollection <DataModel.Game>()); tracker.Setup(t => t.ActiveDeck).Returns(new Deck(trackerFactory.Object)); trackerFactory.Setup(tf => tf.GetTracker()).Returns(tracker.Object); FileVersionInfo expected = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(this.GetType()).Location); Mock <IWinAPI> winApi = new Mock <IWinAPI>(); winApi.Setup(w => w.GetEslFileVersionInfo()).Returns(expected); trackerFactory.Setup(tf => tf.GetService <IWinAPI>()).Returns(winApi.Object); EditGameViewModel model = new EditGameViewModel(trackerFactory.Object); GameOutcome param = GameOutcome.Victory; model.UpdateGameData(param); Assert.IsNotNull(model.Game.ESLVersion); Assert.AreEqual(expected.ProductVersion, model.Game.ESLVersion.ToString()); }
static float CalculateELO(int playerOneRating, int playerTwoRating, GameOutcome outcome) { int eloK = 32; int delta = (int)(eloK * ((int)outcome - ExpectationToWin(playerOneRating, playerTwoRating))); return(delta); }
public GameOutcomeCommandControl(GameOutcome outcome) : this() { this.command = outcome.ResultCommand; this.OutcomeNameTextBox.Text = outcome.Name; this.OutcomeNameTextBox.IsEnabled = false; }
/// <summary> /// Saving user statistics both in the storage and in the json file database /// if user is identified by his/her authorization <paramref name="token"/>. /// </summary> /// <param name="token">User's authorization token.</param> /// <param name="outcome">Game outcome. One of <see cref="GameOutcome"/></param> /// <param name="move">Chosen move option. One of <see cref="MoveOptions"/></param> /// <returns>Returns true if user was found by token, else returns false.</returns> public async Task <bool> SaveAsync(string token, GameOutcome outcome, MoveOptions move) { // get user id var userWithToken = (await _tokens.GetAllAsync()).Where(tk => tk.Item == token).FirstOrDefault(); // if user was not found if (userWithToken == null) { // only one logger message here so as not to litter the file with messages // about saving statistics, since this method will be called very often _logger.LogInformation($"{nameof(StatisticsService)}: User was not identified for saving statistics. The authorization token did not exist or expired."); return(false); } // get user id var userId = userWithToken.Id; // add user statistics to the storage if it doesn't exist await _statistics.AddAsync(new UserStatistics(userId), userId, new StatisticsEqualityComparer()); // change state var record = await _statistics.GetAsync(userId); record.AddRoundInfo(DateTime.Now, outcome, move); // map with StatisticsDb var statisticsToSave = ModelsMapper.ToStatisticsDb(record); //save to file await _jsonDataService.WriteAsync(_options.StatisticsPath + $"{userId}.json", statisticsToSave); return(true); }
/// <summary> /// Saves information and results of the played game round. /// </summary> /// <param name="date">The date of the played round.</param> /// <param name="outcome">The round outcome. One of <see cref="GameOutcome"/></param> /// <param name="move">Player's move. One of <see cref="MoveOptions"/></param> public void AddRoundInfo(DateTime date, GameOutcome outcome, MoveOptions move) { var stringDate = date.ToString("dd.MM.yyyy"); History.TryAdd(stringDate, new GameOutcomeCounts()); History[stringDate].Increment(outcome); IncrementMoveOptionCount(move); }
public void DeleteProbability(GameOutcome outcome) { GameOutcomeProbabilityControl control = this.outcomeProbabilityControls.FirstOrDefault(opc => opc.OutcomeName.Equals(outcome.Name)); if (control != null) { this.outcomeProbabilityControls.Remove(control); } }
public Game(string map, List <Round> rounds, GameOutcome outcome) { Map = map; Rounds = rounds; Outcome = outcome; Terrorists = new List <Player>(); CounterTerrorists = new List <Player>(); }
void OnReceivedGameOutcome(GameOutcome gameOutcome) { var gameOutcomeManager = Instantiate(_GameOutcomePanelPrefab, _Canvas.transform) .GetComponent <GameOutcomePanelManager>(); gameOutcomeManager.GameOutcome = gameOutcome; _GameIsAboutToEnd = true; }
protected override void OnGameEnd(GameOutcome outcome) { Console.WriteLine("OnGameEnd({0})", outcome); if (outcome == GameOutcome.WordGuessed) { Score += 5; } NextPlayer(); }
public void CommandButtonCreateExecuteTest005_CheckIfESLFileVersionAddedWhenESLNOtRunning() { Mock <ITrackerFactory> trackerFactory = new Mock <ITrackerFactory>(); Mock <IMessenger> messanger = new Mock <IMessenger>(); trackerFactory.Setup(tf => tf.GetService <IMessenger>()).Returns(messanger.Object); Mock <ISettings> settings = new Mock <ISettings>(); trackerFactory.Setup(tf => tf.GetService <ISettings>()).Returns(settings.Object); FileVersionInfo expected = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(this.GetType()).Location); Mock <ITracker> tracker = new Mock <ITracker>(); //add two games wit hdiff version - ensure correct is copied tracker.Setup(t => t.Games).Returns(new ObservableCollection <DataModel.Game>() { new DataModel.Game() { Date = DateTime.Now, ESLVersion = new SerializableVersion(new Version(expected.ProductVersion.ToString())) }, new DataModel.Game() { Date = DateTime.Now.AddDays(-7), ESLVersion = new SerializableVersion(2, 3) }, new DataModel.Game() { Date = DateTime.Now, ESLVersion = null }, }); tracker.Setup(t => t.ActiveDeck).Returns(new Deck(trackerFactory.Object)); trackerFactory.Setup(tf => tf.GetTracker()).Returns(tracker.Object); Mock <IWinAPI> winApi = new Mock <IWinAPI>(); //ensure not running winApi.Setup(w => w.GetEslFileVersionInfo()).Returns <FileVersionInfo>(null); trackerFactory.Setup(tf => tf.GetService <IWinAPI>()).Returns(winApi.Object); EditGameViewModel model = new EditGameViewModel(trackerFactory.Object); GameOutcome param = GameOutcome.Victory; model.UpdateGameData(param); Assert.IsNotNull(model.Game.ESLVersion); Assert.AreEqual(expected.ProductVersion, model.Game.ESLVersion.ToString()); }
public void Increment(GameOutcome outcome) { switch (outcome) { case GameOutcome.Win: WinsCount++; break; case GameOutcome.Loss: LossesCount++; break; case GameOutcome.Draw: DrawsCount++; break; default: throw new ArgumentOutOfRangeException(nameof(outcome), "There cannot be another outcome."); } }
protected override void OnGameEnd(GameOutcome outcome) { switch (outcome) { case GameOutcome.WrongWord: Score -= 20; break; case GameOutcome.Surrender: Score /= 5; // Removes 80% (/5 = 20%) break; } NextPlayer(); }
public static string Outcome(GameOutcome outcome) { switch (outcome) { case GameOutcome.TerroristsWin: return("Terrorists"); case GameOutcome.CounterTerroristsWin: return("Counter-Terrorists"); case GameOutcome.Draw: return("Draw"); } throw new ApplicationException("Invalid outcome."); }
// leave game when it is over public Task LeaveGame(Guid gameId, GameOutcome outcome) { // manage game list ListOfActiveGames.Remove(gameId); ListOfPastGames.Add(gameId); // manage running total if (outcome == GameOutcome.Win) wins++; if (outcome == GameOutcome.Lose) loses++; return TaskDone.Done; }
public void GameLoop() { bool playAgain = true; while (playAgain) { string playerInput = Input.GetPlayerInput(); string computerInput = Input.GetComputerInput(); GameOutcome.AnnounceGameOutcome(GameOutcome.CheckForWinner(playerInput, computerInput), playerInput, computerInput); playAgain = Input.PlayAgain(); if (playAgain) { Console.WriteLine(""); } } }
/// <summary> /// This gets called when the game is finished. The parameter has the winning player(s). /// </summary> /// <param name="o"></param> public void GameOver(GameOutcome o) { if (o.Winners.Contains(Player)) { StatusBar.Text = "You won. Congratulations. Banana Stickers and Beer Tickets for everyone!"; } else { //aggregate may be incorrect... can't test right now StatusBar.Text = string.Format("{0} won. Better luck next time.", o.Winners.Aggregate("", (x, y) => { return(x + " & " + y.Name); })); } string scores = Game.Instance.Players .Select(p => String.Format("{0}: {1}{2}", p.Name, p.Score, Environment.NewLine)) .Aggregate((a, b) => String.Concat(a, b)); MessageBox.Show(scores, "Final Scores"); }
private void GameOver() { gameOver = true; GameOverGrid.Visibility = Visibility.Visible; if (player1Won) { GameOverLabel.Content = gameBoard.Player1.Name + " Won"; } else { GameOverLabel.Content = gameBoard.Player2.Name + " Won"; } DataWriter dataWriter = new DataWriter(); GameOutcome newGameOutcome = new GameOutcome(gameBoard.Player1, gameBoard.Player2, player1Won, gameBoard.Turn); gameOutcomes = dataWriter.ReadJson(); gameOutcomes.Add(newGameOutcome); dataWriter.UpdateJson(gameOutcomes); }
// leave game when it is over public Task LeaveGame(Guid gameId, GameOutcome outcome) { // manage game list _activeGames.Remove(gameId); _pastGames.Add(gameId); // manage running total switch (outcome) { case GameOutcome.Win: _wins++; break; case GameOutcome.Lose: _loses++; break; } return(Task.CompletedTask); }
// leave game when it is over public Task LeaveGame(Guid gameId, GameOutcome outcome) { // manage game list ListOfActiveGames.Remove(gameId); ListOfPastGames.Add(gameId); // manage running total if (outcome == GameOutcome.Win) { wins++; } if (outcome == GameOutcome.Lose) { loses++; } return(TaskDone.Done); }
public static long CalculateELOdelta(long teamOneRating, long teamTwoRating, GameOutcome gameResult) { long eloK = 32L; var delta = (eloK * ((long)gameResult - ExpectationToWin(teamOneRating, teamTwoRating))); if (Math.Abs(delta) < 1) { if (delta < 0) { delta = -1; } else { delta = 1; } } return((long)delta); }
async public Task <GameOutcome> Start() { while (States.Count > 0) { var topState = States.Peek(); //currentTime.Advance(); (bool popCurrent, IGameState nextState) = await topState.Execute(); if (popCurrent) { States.Pop(); } if (nextState != null) { States.Push(nextState); } } GameOutcome result = new GameOutcome(); return(result); }
public void TestReverse() { HashSet <GameOutcome> hasWinner = new() { GameOutcome.FirstWin, GameOutcome.SecondWin }; foreach (GameOutcome outcome in Enum.GetValues <GameOutcome>()) { GameOutcome reverse = outcome.Reverse(); if (hasWinner.Contains(outcome)) { Assert.AreNotEqual(outcome, reverse, "Reversed Winner"); Assert.AreEqual(outcome, reverse.Reverse(), "Reversed Winner Twice"); } else { Assert.AreEqual(outcome, reverse, "No Winner"); } } }
private static void CoreUpdate() { s_Outcomes = TicTacToePosition .AllLegalPositions() .ToDictionary(p => p, p => GameOutcome.None); var data = s_Outcomes .Keys .OrderByDescending(key => key.MarkCount); foreach (var position in data) { if (position.Outcome != GameOutcome.None) { s_Outcomes[position] = position.Outcome; continue; } var onMove = position.WhoIsOnMove; GameOutcome bestOutcome = onMove == Mark.Cross ? GameOutcome.SecondWin : GameOutcome.FirstWin; foreach (var next in position.AvailablePositions()) { GameOutcome outcome = s_Outcomes[next]; bestOutcome = onMove == Mark.Cross ? bestOutcome.BestForFirst(outcome) : bestOutcome.BestForSecond(outcome); } s_Outcomes[position] = bestOutcome; } }
/// <summary> /// This gets called when the game is finished. The parameter has the winning player(s). /// </summary> /// <param name="o"></param> public void GameOver(GameOutcome o) { throw new NotImplementedException(); }
/// <summary> /// This gets called when the game is finished. The parameter has the winning player(s). /// </summary> /// <param name="o"></param> public void GameOver(GameOutcome o) { if (o.Winners.Contains(Player)) { StatusBar.Text = "You won. Congratulations. Banana Stickers and Beer Tickets for everyone!"; } else { //aggregate may be incorrect... can't test right now StatusBar.Text = string.Format("{0} won. Better luck next time.", o.Winners.Aggregate("", (x,y) => { return x + " & " + y.Name;})); } string scores = Game.Instance.Players .Select(p => String.Format("{0}: {1}{2}", p.Name, p.Score, Environment.NewLine)) .Aggregate((a, b) => String.Concat(a, b)); MessageBox.Show(scores, "Final Scores"); }
/// <summary> /// Reverse /// </summary> public static GameOutcome Reverse(this GameOutcome value) => value == GameOutcome.FirstWin ? GameOutcome.SecondWin : value == GameOutcome.SecondWin ? GameOutcome.FirstWin : value;