public PreviousDecisionResult ToPlayerSpecific(BaseBot bot) { var result = new PreviousDecisionResult { MatchId = MatchResult.Id }; if (Winner == null) { result.Outcome = RoundOutcome.Tie; } else if (Equals(bot.Competitor, Winner)) { result.Outcome = RoundOutcome.Win; } else { result.Outcome = RoundOutcome.Loss; } if (Equals(bot.Competitor, Player1)) { result.YourPrevious = Player1Played; result.OpponentPrevious = Player2Played; } else { result.YourPrevious = Player2Played; result.OpponentPrevious = Player1Played; } return(result); }
private void AddBot(string token, Mode mode) { logger.Info("Creating new bot. token: " + token); dBWorker.get_bot_id(token); if (this.bots.FindIndex(bot => bot.token == token) < 0) { BaseBot bot = null; switch (mode) { case Mode.FeedBack: { logger.Info("Creating new bot. token."); bot = new FeedbackBot.FeedBackBot(token, this.DBConnectionString); dBWorker.add_bot(token, Mode.FeedBack.ToString()); break; } case Mode.Deffered: { bot = new DefferedPostingBot(token, this.DBConnectionString); dBWorker.add_bot(token, Mode.Deffered.ToString()); break; } } if (bot != null) { bot.Start(); this.bots.Add(bot); } } }
public void OnPost() { List <Competitor> competitors = _db.Competitors.ToList(); if (!competitors.Any()) { competitors = GetDefaultCompetitors(); _db.Competitors.AddRange(competitors); _db.SaveChanges(); } var gameRunner = new GameRunner(); foreach (var competitor in competitors) { BaseBot bot = CreateBotFromCompetitor(competitor); gameRunner.AddBot(bot); } GameRunnerResult gameRunnerResult = gameRunner.StartAllMatches(); SaveResults(gameRunnerResult); BotRankings = gameRunnerResult.GameRecord.BotRecords.OrderByDescending(x => x.Wins).ToList(); AllFullResults = gameRunnerResult.AllMatchResults.OrderBy(x => x.Competitor.Name).ToList(); }
public Fisher(BaseBot Bot, Command command, _userInfo User, CurrencyConfig currency) { this.Bot = Bot; this.command = command; this.User = User; this.currency = currency; }
public async Task <IHttpActionResult> POST(Guid playerID) { // Get the details of this player var player = await database.LoadPlayer(playerID); if (player == null) { return(BadRequest("No player with this ID exists")); } // Retrieve the current state of the game if (player.CurrentGameID.HasValue) { var currentGame = await database.LoadGame(player.CurrentGameID.Value); // Set up a new game, but they are planning the other player var newGame = new Game(); newGame.ID = Guid.NewGuid(); newGame.YellowPlayerID = currentGame.RedPlayerID; newGame.RedPlayerID = currentGame.YellowPlayerID; // Is the player playing against our bot? Yellow goes first. var otherPlayerID = (newGame.RedPlayerID == playerID) ? newGame.YellowPlayerID : newGame.RedPlayerID; if (otherPlayerID == newGame.YellowPlayerID) { var otherPlayer = await database.LoadPlayer(otherPlayerID); if (otherPlayer.SystemBot) { var bot = BaseBot.GetBot(otherPlayerID); await bot.MakeMove(newGame); } // The other player supports http webhooks if (!string.IsNullOrWhiteSpace(otherPlayer.WebHook)) { var bot = BaseBot.GetWebHookBot(otherPlayer.WebHook, otherPlayerID); await bot.MakeMove(newGame); } } using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { // and delete the old game await database.DeleteGame(currentGame.ID); // Create the new game await database.SaveGame(newGame); tx.Complete(); } } else { // For some reason the player doesn't current have a game await CreateInitialGame(playerID); } return(Ok()); }
public static bool AddFisher(BaseBot Bot, Command command, _userInfo User, CurrencyConfig currency) { if (FisherMen.Count(x => x.Key.User.user.user.Equals(User.user.user) && x.Key.currency.Id == currency.Id) == 0) { FisherMen.Add(new Fisher(Bot, command, User, currency), DateTime.Now); return(true); } return(false); }
public BotController([NotNull] TelegramBotClient bot, [NotNull] ReflectionInfo reflectionInfo, [NotNull] PullMethods pullMethods) { this.Bot = new BaseBot(bot); this.Methods = pullMethods; this.Reflection = reflectionInfo; proc = new MessageProcessor(this.Reflection, this.Methods); Init(); }
public async Task <ActionResult> Index(ChangeGameViewModel model) { var allPlayers = await this.database.GetAllPlayers(); var thisPlayer = allPlayers.SingleOrDefault(a => a.Name == model.PlayerName); if (thisPlayer == null) { return(RedirectToAction("Index", "Home")); } var currentGameID = thisPlayer.CurrentGameID; var newGame = new Game(); newGame.ID = Guid.NewGuid(); newGame.YellowPlayerID = model.OtherPlayerID.Value; newGame.RedPlayerID = thisPlayer.ID; var otherPlayer = await database.LoadPlayer(model.OtherPlayerID.Value); if (otherPlayer.SystemBot) { var bot = BaseBot.GetBot(model.OtherPlayerID.Value); await bot.MakeMove(newGame); } // The other player supports http webhooks if (!string.IsNullOrWhiteSpace(otherPlayer.WebHook)) { var bot = BaseBot.GetWebHookBot(otherPlayer.WebHook, model.OtherPlayerID.Value); await bot.MakeMove(newGame); } using (var tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { // and delete the old game if (currentGameID.HasValue) { await database.DeleteGame(currentGameID.Value); } // Delete the other player's previous game. (System bots can play multiple games) if (!otherPlayer.SystemBot && otherPlayer.CurrentGameID.HasValue) { await database.DeleteGame(otherPlayer.CurrentGameID.Value); } // Create the new game await database.SaveGame(newGame); tx.Complete(); } return(RedirectToAction("Index", "DisplayGame", new { gameID = newGame.ID })); }
public RoundResult RunRound(BaseBot player1, BaseBot player2, RoundResult previousResult, IMetrics metrics) { var p1Decision = GetDecision(player1, previousResult, metrics); var p2Decision = GetDecision(player2, previousResult, metrics); BaseBot winner = null; // confirm each has a valid choice bool player1Invalid = IsInvalidDecision(p1Decision, player1); bool player2Invalid = IsInvalidDecision(p2Decision, player2); if (player1Invalid || player2Invalid) { if (player1Invalid && player2Invalid) { // tie - also, what did you do?!?! } else if (player1Invalid) { winner = player2; } else { winner = player1; } } else { if (p1Decision == p2Decision) { // tie } else if (p1Decision.IsWinnerAgainst(ref p2Decision)) { winner = player1; } else { winner = player2; } } var roundResult = new RoundResult { MatchResult = previousResult.MatchResult, Winner = winner?.Competitor, Player1 = player1.Competitor, Player2 = player2.Competitor, Player1Played = p1Decision, Player2Played = p2Decision, }; ApplyDynamiteUsageToBots(player1, p1Decision, player2, p2Decision); return(roundResult); }
private bool IsInvalidDecision(Decision decision, BaseBot bot) { if (decision == Decision.Dynamite) { bool outOfDynamite = (100 - bot.DynamiteUsed) <= 0; return(outOfDynamite); } return(false); }
protected T GetProperty <T>(string propertyName) { var propertyValue = (T)this[propertyName]; if (propertyValue != null || BaseBot == null) { return(propertyValue); } return(BaseBot.GetProperty <T>(propertyName)); }
protected string GetProperty(string propertyName) { var propertyValue = (string)this[propertyName]; // We have to check for empty string since missing string elements are deserialized as string.Empty!? if (!string.IsNullOrEmpty(propertyValue) || BaseBot == null) { return(propertyValue); } return(BaseBot.GetProperty(propertyName)); }
private void ApplyDynamiteUsageToBots(BaseBot player1, Decision p1Decision, BaseBot player2, Decision p2Decision) { if (p1Decision == Decision.Dynamite) { player1.UseDynamite(); } if (p2Decision == Decision.Dynamite) { player2.UseDynamite(); } }
/// <summary> /// Get all rules for whole basedOn hierarchy, starting from root ancestor /// </summary> /// <returns></returns> public IEnumerable <EventRuleElement> GetRules() { if (InheritRules && BaseBot != null) { foreach (var rule in BaseBot.GetRules()) { yield return(rule); } } foreach (var rule in EventRules) { yield return(rule); } }
public string GetSetting(string name) { var setting = BotSettingsConfigurationCollection[name]; if (setting != null) { return(setting.Value); } if (BaseBot == null) { return(null); } return(BaseBot.GetSetting(name)); }
public async Task OnPostAsync() { List <Competitor> competitors = db.Competitors.ToList(); if (!competitors.Any()) { competitors = GetDefaultCompetitors(); db.Competitors.AddRange(competitors); db.SaveChanges(); } var gameRunner = new GameRunner(metrics); foreach (var competitor in competitors) { BaseBot bot = CreateBotFromCompetitor(competitor); gameRunner.AddBot(bot); } var stopwatch = System.Diagnostics.Stopwatch.StartNew(); GameRunnerResult gameRunnerResult = gameRunner.StartAllMatches(); stopwatch.Stop(); var metric = new Dictionary <string, double> { { "GameLength", stopwatch.Elapsed.TotalMilliseconds } }; // Set up some properties: var properties = new Dictionary <string, string> { { "Source", configuration["P20HackFestTeamName"] } }; // Send the event: metrics.TrackEventDuration("GameRun", properties, metric); SaveResults(gameRunnerResult); BotRankings = gameRunnerResult.GameRecord.BotRecords.OrderByDescending(x => x.Wins).ToList(); AllFullResults = gameRunnerResult.AllMatchResults.OrderBy(x => x.Competitor.Name).ToList(); //Get 20 Last GamesForTable = db.GameRecords.OrderByDescending(g => g.GameDate).Take(20).Include(g => g.BotRecords).ToList(); if (bool.Parse(configuration["EventGridOn"])) { await PublishMessage(BotRankings.First().GameRecord.Id.ToString(), BotRankings.First().Competitor.Name); } }
internal Decision GetDecision(BaseBot player, RoundResult previousResult, IMetrics metrics) { var stopwatch = System.Diagnostics.Stopwatch.StartNew(); var d = player.GetDecision(previousResult.ToPlayerSpecific(player)); stopwatch.Stop(); var metric = new Dictionary <string, double> { { "DecisionTime", stopwatch.Elapsed.TotalMilliseconds } }; var properties = new Dictionary <string, string> { { "Bot", player.Name } }; metrics.TrackEventDuration("BotDesicionTime", properties, metric); return(d); }
public async Task <string> PostAsync() { List <Competitor> competitors = db.Competitors.ToList(); var gameRunner = new GameRunner(metrics); foreach (var competitor in competitors) { BaseBot bot = CreateBotFromCompetitor(competitor); gameRunner.AddBot(bot); } var stopwatch = System.Diagnostics.Stopwatch.StartNew(); GameRunnerResult gameRunnerResult = gameRunner.StartAllMatches(); stopwatch.Stop(); var metric = new Dictionary <string, double> { { "GameLength", stopwatch.Elapsed.TotalMilliseconds } }; // Set up some properties: var properties = new Dictionary <string, string> { { "Source", configuration["P20HackFestTeamName"] } }; // Send the event: metrics.TrackEventDuration("GameRun", properties, metric); SaveResults(gameRunnerResult); var winner = gameRunnerResult.AllMatchResults.Select(x => x.MatchResults).First().First().Player1.Name; await PublishMessage(gameRunnerResult.GameRecord.Id.ToString(), winner); //return gameRunnerResult.AllMatchResults.Select(x => x.MatchResults).First().First().Player1.Name; var bestRecord = gameRunnerResult.GameRecord.BotRecords.OrderByDescending(x => x.Wins).First(); return($"{bestRecord.Competitor.Name}:{bestRecord.Wins}-{bestRecord.Losses}"); }
private MatchResult GetMatchResultFromRoundResults(MatchResult matchResult, BaseBot player1, List <RoundResult> roundResults) { var winner = roundResults.GroupBy(x => x.Winner).OrderByDescending(x => x.Count()).Select(x => x.Key).First(); if (winner == null) { matchResult.WinningPlayer = MatchOutcome.Neither; } else if (Equals(winner, player1.Competitor)) { matchResult.WinningPlayer = MatchOutcome.Player1; } else { matchResult.WinningPlayer = MatchOutcome.Player2; } matchResult.RoundResults = roundResults; return(matchResult); }
public MatchResult RunMatch(BaseBot player1, BaseBot player2) { var roundResults = new List <RoundResult>(); var roundRunner = new RoundRunner(); var matchResult = new MatchResult { Player1 = player1.Competitor, Player2 = player2.Competitor }; RoundResult previousResult = new RoundResult { MatchResult = matchResult }; for (int i = 0; i < 100; i++) { previousResult = roundRunner.RunRound(player1, player2, previousResult, metrics); roundResults.Add(previousResult); } return(GetMatchResultFromRoundResults(matchResult, player1, roundResults)); }
public static async Task HandleMessage(Message message, BaseBot Bot, CurrencyConfig currency) { _userInfo bank = CacheHandler.FindUser(message.sender, currency); Rewards.MessageRewardUser(bank); string[] iams = { "i am", "i'm", "im" }; int index; string msg = message.body.ToLower(); foreach (string iam in iams) { if (msg.Contains(iam)) { index = msg.IndexOf(iam) + iam.Length; string newMsg = msg.Substring(index, msg.Length - index).Trim(); await Bot.SendMessage(message, $"Hi {newMsg}, Im Dad", currency); break; } } }
public void AddBot(BaseBot bot) { _competitors.Add(bot); }
public async Task <IHttpActionResult> POST(Guid playerID, int columnNumber, string password) { // Get the details of this player var player = await database.LoadPlayer(playerID); if (player == null) { return(BadRequest("The player with this ID does not exist")); } if (player.Password != password) { var response = new HttpResponseMessage(HttpStatusCode.Forbidden); response.ReasonPhrase = "Incorrect Password"; return(ResponseMessage(response)); } // Retrieve the current state of the game var game = await database.LoadGame(player.CurrentGameID.Value); if (game == null) { return(BadRequest("Your player is not currently playing a game. Call NewGame")); } if (game.CurrentState != Models.GameState.RedToPlay && game.CurrentState != Models.GameState.YellowToPlay) { throw new Exception("This game is not playable"); } // Is it the players turn var playerIsYellow = (game.YellowPlayerID == player.ID); if (playerIsYellow && !game.YellowToPlay()) { throw new Exception("It is RED's turn to play. You are YELLOW."); } if ((!playerIsYellow) && game.YellowToPlay()) { throw new Exception("It is YELLOW's turn to play. You are RED."); } // Is the move allowed? if (!game.IsMoveAllowed(columnNumber)) { throw new Exception("Sorry that move is not allowed"); } // Has the player won? game.MakeMove(playerIsYellow, columnNumber); // Store away the updated game await database.SaveGame(game); // Is the player playing against our bot? if (game.CurrentState == Models.GameState.RedToPlay || game.CurrentState == Models.GameState.YellowToPlay) { var otherPlayerID = (game.RedPlayerID == playerID) ? game.YellowPlayerID : game.RedPlayerID; var otherPlayer = await database.LoadPlayer(otherPlayerID); if (otherPlayer.SystemBot) { var bot = BaseBot.GetBot(otherPlayerID); await bot.MakeMove(game); await database.SaveGame(game); } // The other player supports http webhooks if (!string.IsNullOrWhiteSpace(otherPlayer.WebHook)) { var bot = BaseBot.GetWebHookBot(otherPlayer.WebHook, otherPlayerID); await bot.MakeMove(game); await database.SaveGame(game); } } return(Ok()); }
public static async Task HandleCommand(Command command, BaseBot Bot, CurrencyConfig currency) { _userInfo[] tBanks = CacheHandler.FindUsers(command.mentions, currency); _userInfo bank = CacheHandler.FindUser(command.sender, currency); switch (command.commandStr) { //case "echo": // await Bot.SendMessage(command.channel, command.commandArgString, command.Source, currency); // break; //case "echodm": // await Bot.SendDM(command.sender, command.commandArgString, command.Source, currency); // break; //case "wtf": // new Thread(async() => await Bot.SendMessage(command, "{User} this was sent from another thread", currency)).Start(); //// //Streamlabs.CreateDonation("Jamm", 1, botConfig.Streamlabs); //// await Bot.SendMessage(command.channel, Streamlabs.GetDonations(botConfig.Streamlabs).ToString()); // break; //case null when currency.BalanceCommands.Contains(command.commandStr): // break; case string S when currency.BalanceCommands.Contains(command.commandStr): if (command.mentions.Length == 0) { await Bot.SendMessage(command, "{User} You Have {Value} {Currency}", currency, bank.balance); } else { await Bot.SendMessage(command, "{User} {User0} Has {Value} {Currency}", currency, tBanks[0].balance); } break; case string S when currency.PayCommands.Contains(command.commandStr): if (command.mentions.Length > 0 && command.values.Length > 0) { if (bank.balance >= command.values[0]) { bank.balance -= command.values[0]; tBanks[0].balance += command.values[0]; bank.Update(); tBanks[0].Update(); await Bot.SendMessage(command, "{User} Paid {Value0} {Currency} To {User0}", currency); } else { await Bot.SendMessage(command, "{User} You Only Have {Value} {Currency}", currency, bank.balance); } } else { await Bot.SendMessage(command, "{User} You Havent Specifided Who And/Or How Much To Pay", currency); } break; case string S when currency.FishCommands.Contains(command.commandStr): if (Rewards.AddFisher(Bot, command, bank, currency)) { await Bot.SendMessage(command, "{User} You Started Fishing", currency); bank.balance -= currency.FishCost; bank.Update(); } else { await Bot.SendMessage(command, "{User} You Are Already Fishing!", currency); } break; case string S when currency.GambleCommands.Contains(command.commandStr): if (command.values.Length > 0) { int Num = Controller.rnd.Next(0, 100); if (currency.GambleOdds > Num) { bank.balance += command.values[0]; bank.Update(); await Bot.SendMessage(command, "{User} You Won {Value} {Currency}", currency, command.values[0]); } else { bank.balance -= command.values[0]; bank.Update(); await Bot.SendMessage(command, "{User} You Lost {Value} {Currency}", currency, command.values[0]); } } else { await Bot.SendMessage(command, "{User} You Didnt Specify a Value", currency); } break; default: if (currency.SimpleResponses.ContainsKey(command.commandStr)) { await Bot.SendMessage(command, currency.SimpleResponses[command.commandStr], currency); } break; } }