static Pokémon[] GetPokémon(string fileName) { StreamReader Plist = new StreamReader(fileName); Pokémon[] pokémons = new Pokémon[fetchSize(fileName)[1]]; string[] line = new string[] {}; for (int i = 0; i < fetchSize(fileName)[1]; i++) { line = Plist.ReadLine().Split(','); Pokémon pokémon = new Pokémon(); pokémon.natNum = Convert.ToInt32(line[0]); pokémon.name = line[1]; pokémon.type1Num = Convert.ToInt32(line[2]); pokémon.type2Num = Convert.ToInt32(line[3]); pokémon.ability1Num = Convert.ToInt32(line[4]); pokémon.ability2Num = Convert.ToInt32(line[5]); pokémon.ability3Num = Convert.ToInt32(line[6]); pokémon.HP = Convert.ToInt32(line[7]); pokémon.A = Convert.ToInt32(line[8]); pokémon.D = Convert.ToInt32(line[9]); pokémon.spA = Convert.ToInt32(line[10]); pokémon.spD = Convert.ToInt32(line[11]); pokémon.S = Convert.ToInt32(line[12]); pokémons[i] = pokémon; } Plist.Close(); return(pokémons); }
/// <summary> /// Uses the specified move, as invoked by the <paramref name="user"/> on the <paramref name="defender"/> /// </summary> /// <param name="user">The user of the <paramref name="move"/>.</param> /// <param name="move">The move being used.</param> /// <param name="defender">The defender whom the <paramref name="move"/> is being used upon.</param> /// <returns>The amount of damage done by the move.</returns> public static int Use(this Pokémon user, Move move, Pokémon defender) { int initialHP = defender.RemainingHealth; move.Use(user, defender); int laterHP = defender.RemainingHealth; return(initialHP - laterHP); }
private int DoTurn(Pokémon actor, Pokémon enemy, IPokéAgent ai) { //Perform the turn according to the given AI int damageDone = actor.Use(ai.ChooseMove(this), enemy); //Print out remaining HP of enemy Console.WriteLine("\t" + enemy.Species.Name + " has " + enemy.RemainingHealth + " health remaining."); return(damageDone); }
public static int UseMoveOfType(this Pokémon user, Type t, Pokémon defender) { List <Move> availableMoves = user.Moves.Where(move => move.AttackType == t).ToList(); if (availableMoves.Count < 1) { throw new Exception( $"Pokémon {user.Species.Name} asked to use a move of a type {Enum.GetName(typeof(Type), t)}, of which it does not have any."); } Move moveChoice = availableMoves[new Random().Next(availableMoves.Count)]; return(Use(user, moveChoice, defender)); }
private int GetHealthQuadrant(Pokémon p) { //Get the ratio of pokemon's current health to total health double approx = p.RemainingHealth / (double)p.Stats[PokémonAPI.Stat.HP]; //Put the ratio on a scale of 1 to 4 (instead of 0.0 to 1.0) //0 = dead, so we don't have to worry about this case //1 = 1-25% //2 = 26-50% //3 = 51-75% //4 = 76-100% approx = approx * 4; return((int)Math.Ceiling(approx)); }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } Pokémon = await _context.Pokémon.FirstOrDefaultAsync(m => m.ID == id); if (Pokémon == null) { return(NotFound()); } return(Page()); }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } Pokémon = await _context.Pokémon.FindAsync(id); if (Pokémon != null) { _context.Pokémon.Remove(Pokémon); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
private static int ComparePokémonSpeed(Pokémon p1, Pokémon p2) { if (p1.Stats[PokémonAPI.Stat.Speed] > p2.Stats[PokémonAPI.Stat.Speed]) { //First 'mon is faster than second 'mon return(1); } else if (p1.Stats[PokémonAPI.Stat.Speed] < p2.Stats[PokémonAPI.Stat.Speed]) { //First 'mon is slower than second 'mon return(-1); } else { //First 'mon is just as fast as second 'mon return(0); } }
static double Damage(int level, Move move, Pokémon p1, Pokémon p2, int modifier) { double damage = (((((2 * level / 5) + 2) * move.power * (p1.A / p2.D)) / 50) + 2) * modifier; return(damage); }
private static void Main(string[] args) { /**Region for setting up SARSA function (and possibly parameters)**/ #region SARSA Setup //Set up SARSA object var explorationPolicy = new EpsilonGreedyExploration(ExplorationRate); var numberOfStates = 15 * 15 * 15 * 15; var numberOfActions = Enum.GetValues(typeof(Type)).Length; var sarsa = new SARSA(numberOfStates, numberOfActions, explorationPolicy); //Prepare the state mapping Func <Pokémon, Pokémon, long> getState = (pokémon1, pokémon2) => { var moveTypes = pokémon1.Moves.Select(t => t.AttackType).Distinct().ToList(); return (15 * 15 * 15 * (long)pokémon1.Types[0] + 15 * 15 * (long)(pokémon1.Types.Count > 1 ? pokémon1.Types[1] : pokémon1.Types[0]) + 15 * (long)pokémon2.Types[0] + 1 * (long)(pokémon2.Types.Count > 1 ? pokémon2.Types[1] : pokémon2.Types[0])); }; #endregion SARSA Setup using (var sw = new StreamWriter("PineappleExpress.txt")) { sw.Write(""); } /**Region for setting up the battle itself**/ #region Battle Execution //For the specified number of battles, perform battles and update the policy for (var battleNumber = 0; battleNumber < NumberOfBattles; battleNumber++) { // set exploration rate for this iteration explorationPolicy.ExplorationRate = ExplorationRate - (double)battleNumber / NumberOfBattles * ExplorationRate; // set learning rate for this iteration sarsa.LearningRate = LearningRate - (double)battleNumber / NumberOfBattles * LearningRate; //Prepare the Pokémon Pokémon pokemon1 = RentalPokémon.RentalPorygon; //A pre-made Porygon Pokémon pokemon2 = RentalPokémon.RentalVenusaur; //A pre-made opponent long previousState = -1; var previousAction = -1; long currentState = -1; var nextAction = -1; var reward = 0.0; var firstTurn = true; double percentFinished = 0; //Battle loop while (!(pokemon1.IsFainted || pokemon2.IsFainted)) { //Shift states currentState = getState(pokemon1, pokemon2); var validTypes = pokemon1.Moves.Select(m => (int)m.AttackType).Distinct().ToList(); nextAction = sarsa.GetAction(currentState, validTypes); //update SARSA if (!firstTurn) { sarsa.UpdateState(previousState, previousAction, reward, currentState, nextAction); } else { firstTurn = false; } //Determine who moves first var firstMover = pokemon1.Stats[Stat.Speed] > pokemon2.Stats[Stat.Speed] ? pokemon1 : pokemon2; //Perform actions if (pokemon1 == firstMover) { reward = pokemon1.UseMoveOfType((Type)nextAction, pokemon2); Console.WriteLine("{0} (Pokémon 1) used a move of type {1}", pokemon1.Species.Name, Enum.GetName(typeof(Type), (Type)nextAction)); Console.WriteLine("Did {0} damage. {1} (Pokémon 2) now has {2} health remaining)", reward, pokemon2.Species.Name, pokemon2.RemainingHealth); Console.WriteLine(((Type)nextAction).MultiplierOn(pokemon2.Types.ToArray())); if (!pokemon2.IsFainted) { pokemon2.Use(new Random().Next(4), pokemon1); } else { reward += 20; } } else { pokemon2.Use(new Random().Next(4), pokemon1); //Console.WriteLine("{0} (Pokémon 2) used {1}", pokemon2.Species.Name, pokemon2.Moves[0].Name); //Console.WriteLine("Did {0} damage. {1} (Pokémon 1) now has {2} health remaining)", // reward, pokemon1.Species.Name, pokemon1.RemainingHealth); if (!pokemon1.IsFainted) { reward = pokemon1.UseMoveOfType((Type)nextAction, pokemon2); Console.WriteLine("{0} (Pokémon 1) used a move of type {1}", pokemon1.Species.Name, Enum.GetName(typeof(Type), (Type)nextAction)); Console.WriteLine("Did {0} damage. {1} (Pokémon 2) now has {2} health remaining)", reward, pokemon2.Species.Name, pokemon2.RemainingHealth); Console.WriteLine(((Type)nextAction).MultiplierOn(pokemon2.Types.ToArray())); } } previousState = currentState; previousAction = nextAction; percentFinished = ((double)pokemon2.Stats[Stat.HP] - pokemon2.RemainingHealth) / pokemon2.Stats[Stat.HP]; Console.WriteLine($"{reward}"); } sarsa.UpdateState(previousState, previousAction, reward, currentState, nextAction); if (pokemon1.IsFainted) { Console.WriteLine("{0} (Pokémon 1) Fainted", pokemon1.Species.Name); } else { Console.WriteLine("{0} (Pokémon 2) Fainted", pokemon2.Species.Name); } //Print score for graphing using (var sw = new StreamWriter($"PineappleExpress({ExplorationRate}_{LearningRate}).txt", true)) { sw.WriteLine("{0}, {1}", battleNumber, percentFinished); } } #endregion Battle Execution }
/// <summary> /// Uses the specified move, as invoked by the <paramref name="user"/> on the <paramref name="defender"/> /// </summary> /// <param name="user">The user of the move.</param> /// <param name="moveIndex">The index corresponding to which of the <paramref name="user"/>'s moves to use.</param> /// <param name="defender">The defender whom the move is being used upon.</param> /// <returns>The amount of damage done by the move.</returns> public static int Use(this Pokémon user, int moveIndex, Pokémon defender) => Use(user, user.Moves[moveIndex], defender);
static void Main(string[] args) { /* * //TESTING PORTION * //A pre-made Porygon * Pokémon pokemon1 = RentalPokémon.RentalPorygon; * //A pre-made Venusaur * Pokémon pokemon2 = RentalPokémon.RentalVenusaur; * Console.WriteLine("Porygon health: " + pokemon1.RemainingHealth); * Console.WriteLine("Venusaur health: " + pokemon2.RemainingHealth); * * //An example of Porygon attacking Venusaur * int damageDealt = pokemon1.Use(2, pokemon2); * Console.WriteLine("Damage dealt by Porygon: " + damageDealt); * * //Checking remaining health * int p1Remaining = pokemon1.RemainingHealth; * int p2Remaining = pokemon2.RemainingHealth; * Console.WriteLine("Porygon health: " + p1Remaining); * Console.WriteLine("Venusaur health: " + p2Remaining); * * //See if Pokémon has fainted * bool hasFainted = pokemon2.IsFainted; * Console.WriteLine("Did Venusaur faint? " + hasFainted); */ //Do the experiment a certain number of times int numIterations = 30; //Perform a number of pokemon battles each iteration int numBattles = 20000; //Keep track of running sums for averaging later List <int> runningSumOfRewards = new List <int>(); List <double> averageOfRewards = new List <double>(); for (int j = 0; j < numBattles; ++j) { runningSumOfRewards.Add(0); averageOfRewards.Add(0); } for (int j = 1; j <= numIterations; ++j) { //Track stats int agentWins = 0; int opponentWins = 0; //Create the AI for our battles IntelligentPokéAgent agentAi = new IntelligentPokéAgent(); //Initialize learning algorithm agentAi.EstimateRewards(); //These are for the comparison algorithm, a SARSA algorithm from accord.net machine learning library /* * var epol = new EpsilonGreedyExploration(IntelligentPokéAgent.EPSILON); * var tpol = new TabuSearchExploration(IntelligentPokéAgent.ACTION_SPACE, epol); * var sarsa = new Sarsa(IntelligentPokéAgent.STATE_SPACE, IntelligentPokéAgent.ACTION_SPACE, tpol); * agentAi.comparisonAlgorithm = sarsa; */ //agentAi.qlearn.LearningRate = IntelligentPokéAgent.ALPHA; //agentAi.qlearn.DiscountFactor = IntelligentPokéAgent.GAMMA; RandomPokéAgent opponentAi = new RandomPokéAgent(); //SmartPokéAgent opponentAi = new SmartPokéAgent(); //Borrow some already-created pokemon for the battle List <Pokémon> agents = new List <Pokémon>(); Pokémon agent1 = RentalPokémon.RentalVenusaur; Pokémon agent2 = RentalPokémon.RentalBlastoise; Pokémon agent3 = RentalPokémon.RentalCharizard; Pokémon agent4 = RentalPokémon.RentalPorygon; Pokémon agent5 = RentalPokémon.RentalGengar; agents.Add(agent1); agents.Add(agent2); agents.Add(agent3); agents.Add(agent4); agents.Add(agent5); List <Pokémon> opponents = new List <Pokémon>(); Pokémon opponent1 = RentalPokémon.RentalVenusaur; Pokémon opponent2 = RentalPokémon.RentalBlastoise; Pokémon opponent3 = RentalPokémon.RentalCharizard; Pokémon opponent4 = RentalPokémon.RentalPorygon; Pokémon opponent5 = RentalPokémon.RentalGengar; opponents.Add(opponent1); opponents.Add(opponent2); opponents.Add(opponent3); opponents.Add(opponent4); opponents.Add(opponent5); Pokémon agent; Pokémon opponent; Battle testBattle = new Battle(); //Battle for (int i = 0; i < numBattles; ++i) { //Start a new episode agentAi.StartNewBattleEpisode(); //Decrease exploration rate gradually agentAi.variableEpsilon = IntelligentPokéAgent.EPSILON - (i / (double)numBattles) * IntelligentPokéAgent.EPSILON; //agentAi.variableEpsilon *= IntelligentPokéAgent.EPSILON_DECAY; /* * //TESTING - reset stuff for this battle * epol.Epsilon = IntelligentPokéAgent.EPSILON - (i / (double)numBattles) * IntelligentPokéAgent.EPSILON; * //agentAi.qlearn.LearningRate = IntelligentPokéAgent.ALPHA - (i / (double)numBattles) * IntelligentPokéAgent.ALPHA; * tpol.ResetTabuList(); */ //Get a random agent and opponent agent = agents[rnd.Next(agents.Count)]; //agent = agent4; //porygon is a good agent opponent = opponents[rnd.Next(opponents.Count)]; //opponent = opponent1; //venusaur is a simple opponent while (opponent.Species.Name == agent.Species.Name) { //No doubles opponent = opponents[rnd.Next(opponents.Count)]; } //~~~~~~~~~~~~~~~~~~~~~TESTING: what if pokemon had much more health?~~~~~~~~~~~~~~~~~~~~~~~~~~~ //agent.Stats[Stat.HP] = 1000; //opponent.Stats[Stat.HP] = 1000; agent.Heal(); opponent.Heal(); //Print battle text to console Console.WriteLine("~~~~~ITERATION " + j + ", BATTLE " + (i + 1) + "~~~~~"); Console.WriteLine("A wild " + opponent.Species.Name + " appears! Go, " + agent.Species.Name + "!"); //Do the battle and record the winner Pokémon winner = testBattle.DoBattle(agent, agentAi, opponent, opponentAi); //Print winner to console Console.WriteLine("The winner is " + winner.Species.Name + ", with " + winner.RemainingHealth + " HP left!\n"); //Increment stats if (winner == agent) { agentWins++; } else { opponentWins++; } //Refresh pokemon health agent.Heal(); opponent.Heal(); } //Print out stats Console.WriteLine("Out of " + numBattles + " battles:"); Console.WriteLine("\tThe agent won " + agentWins + " times."); Console.WriteLine("\tThe opponent won " + opponentWins + " times."); /* * Console.WriteLine("Agent total reward per battle: "); * for (int i = 0; i < numBattles; ++i) * { * //Write rewards in a cluster * Console.Write("" + agentAi.myRewards[i]); * if (i == numBattles - 1) { Console.WriteLine(); } * else { Console.Write(", "); } * * //Write rewards by line * //Console.WriteLine("\tBattle #" + (i+1) + ": " + agentAi.myRewards[i]); * } */ //Write rewards to file for graphing //String outputFile = "rewarddata" + j + ".txt"; //using (System.IO.StreamWriter outputWriter = new System.IO.StreamWriter(outputFile)) //{ for (int i = 0; i < numBattles; ++i) { //outputWriter.WriteLine("" + i + ", " + agentAi.myBattleRewards[i]); //Also add to the running sums runningSumOfRewards[i] += agentAi.myBattleRewards[i]; } //} /* * outputFile = "rewarddata" + j + ".csv"; * using (System.IO.StreamWriter outputWriter = new System.IO.StreamWriter(outputFile)) * { * for (int i = 0; i < numBattles; ++i) * { * outputWriter.WriteLine("" + i + ", " + agentAi.myBattleRewards[i]); * } * } */ } //Finally, go through and average all the rewards from all the iterations for (int j = 0; j < numBattles; ++j) { averageOfRewards[j] = (int)Math.Round(runningSumOfRewards[j] / (double)numIterations); } //Finally, write the averages to an outfile String outputFileAvg = "rewarddata_averages.txt"; using (System.IO.StreamWriter outputWriter = new System.IO.StreamWriter(outputFileAvg)) { for (int i = 0; i < numBattles; ++i) { outputWriter.WriteLine("" + i + ", " + averageOfRewards[i]); } } //Done return; }
private async void BtnSearch_Click(object sender, RoutedEventArgs e) { var invoer = TxtSearch.Text; if (string.IsNullOrWhiteSpace(invoer)) { MessageBox.Show("Gelieve de naam of een id van een Pokémon op te geven...", "Ongeldige invoer", MessageBoxButton.OK, MessageBoxImage.Error); TxtSearch.Focus(); } else { PokémonDto pkmnDto; PokémonSpeciesDto speciesDto; GUIEnabled(false); //haal pokémoninfo uit cache if (int.TryParse(invoer, out int pokéId)) { // gebruiker heeft nummer ingevoerd pkmnDto = pokéCache.PokémonDtos.Where(x => x?.id == pokéId).FirstOrDefault(); } else { // gebruiker heeft naam ingevoerd pkmnDto = pokéCache.PokémonDtos.Where(x => x?.name == invoer.ToLower()).FirstOrDefault(); } // indien cache geen info over gezochte pokémon bevat, downloaden... if (pkmnDto != null) { speciesDto = pokéCache.PokémonSpeciesDtos[pkmnDto.id]; } else { // download info van API var pkmnTask = Task.Run(() => pokemonClient.DownloadString(invoer)); var speciesTask = Task.Run(() => pokemonSpeciesClient.DownloadString(invoer)); await Task.WhenAll(pkmnTask, speciesTask); // deserialiseren van JSON string naar DTO object pkmnDto = JsonConvert.DeserializeObject <PokémonDto>(pkmnTask.Result); speciesDto = JsonConvert.DeserializeObject <PokémonSpeciesDto>(speciesTask.Result); // DTO opslaan in cache voor hergebruik pokéCache.PokémonDtos[pkmnDto.id] = pkmnDto; } currentPokémon = new Pokémon() { Name = pkmnDto.name.FirstToUpper(), Attack = pkmnDto.stats.Where(stat => stat.stat.name == "attack").Select(stat => stat.base_stat).First(), Defense = pkmnDto.stats.Where(stat => stat.stat.name == "defense").Select(stat => stat.base_stat).First(), HP = pkmnDto.stats.Where(stat => stat.stat.name == "hp").Select(stat => stat.base_stat).First(), Types = pkmnDto.types.Select(type => type.type.name).ToList(), Description = speciesDto?.flavor_text_entries.Where(x => x.language.name == "en").Select(x => x.flavor_text).First(), ImageUrl = pkmnDto.sprites.front_default }; UpdateGUI(); GUIEnabled(true); } }
public Pokémon DoBattle(Pokémon agentPokémon, IntelligentPokéAgent agentAi, Pokémon defenderPokémon, IPokéAgent defenderAi) { //Store variables agent = agentPokémon; defender = defenderPokémon; //Reset agent state agentAi.ResetState(this); //Print log to console //Console.WriteLine("RL STATE NUMBER: " + agentAi.currentState); Console.WriteLine("\tLevel " + agent.Level + " " + agent.Species.Name + " has " + agent.RemainingHealth + " health."); /* * Console.WriteLine("\t\tAttack " + agent.Stats[Stat.Attack]); * Console.WriteLine("\t\tDefense " + agent.Stats[Stat.Defense]); * Console.WriteLine("\t\tHP " + agent.Stats[Stat.HP]); * Console.WriteLine("\t\tSpecial " + agent.Stats[Stat.Special]); * Console.WriteLine("\t\tSpeed " + agent.Stats[Stat.Speed]); */ Console.WriteLine("\tLevel " + defender.Level + " " + defender.Species.Name + " has " + defender.RemainingHealth + " health."); /* * Console.WriteLine("\t\tAttack " + defender.Stats[Stat.Attack]); * Console.WriteLine("\t\tDefense " + defender.Stats[Stat.Defense]); * Console.WriteLine("\t\tHP " + defender.Stats[Stat.HP]); * Console.WriteLine("\t\tSpecial " + defender.Stats[Stat.Special]); * Console.WriteLine("\t\tSpeed " + defender.Stats[Stat.Speed]); */ //Perform the battle until one pokemon has fainted bool weFainted = false; bool theyFainted = false; while (true) { agentAi.StartNewTurnEpisode(); //Fastest pokemon goes first //TODO: what do we do if speed is the same? if (ComparePokémonSpeed(agent, defender) >= 0) { //We are faster //Agent pokemon's turn agentReward = DoTurn(agent, defender, agentAi); agentAi.ApplyRewardDealDamage(agentReward); //~~~~~~~~~~~~~~~TESTING: what if ice beam is much more effective?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //if (agentAi.lastAction == 0) { defender.Damage += 100; } //Did they faint? if (defender.IsFainted) { theyFainted = true; } else { //Opponent pokemon's turn agentReward = DoTurn(defender, agent, defenderAi); agentAi.ApplyRewardTakeDamage(agentReward); //Did we faint? if (agent.IsFainted) { weFainted = true; } } //Console.WriteLine("\t\tFrom state " + agentAi.lastState + " to state " + agentAi.currentState + //" by action " + agentAi.lastAction + " for reward " + agentAi.lastReward + "."); } else { //Opponent is faster //Opponent pokemon's turn agentReward = DoTurn(defender, agent, defenderAi); agentAi.ApplyRewardTakeDamage(agentReward); //Did we faint? if (agent.IsFainted) { weFainted = true; } else { //Agent pokemon's turn agentReward = DoTurn(agent, defender, agentAi); agentAi.ApplyRewardDealDamage(agentReward); //Did they faint? if (defender.IsFainted) { theyFainted = true; } } //Console.WriteLine("\t\tFrom state " + agentAi.lastState + " to state " + agentAi.currentState); } //If someone fainted, assign additional reward for winning or losing the battle if (weFainted) { agentAi.ApplyRewardLose(); } if (theyFainted) { agentAi.ApplyRewardWin(); } //Update the learner agentAi.LearnerUpdate(this); //Console.WriteLine("\t\tFrom state " + agentAi.lastState + " to state " + agentAi.currentState + //" by action " + agentAi.lastAction + " for reward " + agentAi.lastReward + "."); //If someone fainted, break the loop if (weFainted || theyFainted) { break; } } //The battle is over //Return the winning pokemon if (weFainted) { return(defender); } else { return(agent); } }
public async Task PokemonInfo( [Summary("Pokémon's name to search. Must be in quotes if there are spaces.")] params string[] pokeNameStrings) { string pokeName = string.Join(" ", pokeNameStrings); await this.Context.Channel.TriggerTypingAsync(); string parsedImageUrl = string.Empty; try { if (PokéDex.InstanceDex == null) { new PokéDex(); } if (PokéDex.InstanceDex == null) { Console.WriteLine("[Command 'pokeinfo']: Instance is still null!"); return; } Pokémon requestedPokémon = PokéDex.InstanceDex.AllPokémon.FirstOrDefault(e => string.Equals(e.SpeciesName, pokeName, StringComparison.CurrentCultureIgnoreCase) || int.TryParse(pokeName, out int result) && e.DexNum == result); if (requestedPokémon == null) { await this.ReplyAsync($"Pokémon '{pokeName}' not found! {(pokeName.ToLower() == "nidoran" ? "\nNidoran Requires '-F' or '-M' to indicate gender." : string.Empty)}"); return; } EmbedBuilder builder = new EmbedBuilder { Title = requestedPokémon.SpeciesName, Footer = new EmbedFooterBuilder { Text = $"#{requestedPokémon.DexNum}" } }; parsedImageUrl = $"https://play.pokemonshowdown.com/sprites/xyani/{requestedPokémon.SpeciesName}.gif"; parsedImageUrl = parsedImageUrl.Replace("Mime Jr.", "mimejr").Replace("Mr. Mime", "mrmime").Replace("Type: Null", "typenull").Replace("Nidoran-F", "nidoranf").Replace("Nidoran-M", "nidoranm").Replace("Ho-Oh", "hooh").Replace("Hakamo-o", "hakamoo").Replace("Kammo-o", "kammoo").Replace("Porygon-Z", "porygonz").Replace("Zygarde-10%", "zygarde-10").ToLower(); // Currently has issues // builder.ThumbnailUrl = parsedImageUrl; // So we do this instead :^) System.Drawing.Image image = null; if (HttpHelper.UrlExists(parsedImageUrl)) { byte[] imageBytes = await Program.Instance.HttpClient.GetByteArrayAsync(parsedImageUrl); using (MemoryStream ms = new MemoryStream(imageBytes)) { image = Image.FromStream(ms); } } if (image != null) { if (File.Exists(Path.Combine(this.AppPath, "pokemon.gif"))) { File.Delete(Path.Combine(this.AppPath, "pokemon.gif")); } image.Save(Path.Combine(this.AppPath, "pokemon.gif")); await this.Context.Channel.SendFileAsync(Path.Combine(this.AppPath, "pokemon.gif")); } // Back to your regularlly scheduled builder builder.WithColor(requestedPokémon.Color.Name == "Brown" ? Color.FromArgb(40, 26, 13) : requestedPokémon.Color); builder.Fields.Add(new EmbedFieldBuilder { IsInline = true, Name = "Prevolution", Value = requestedPokémon.EvolvesFrom == null ? "No prevolution" : string.Join(", ", requestedPokémon.EvolvesFrom) }); builder.Fields.Add(new EmbedFieldBuilder { IsInline = true, Name = "Evolutions", Value = requestedPokémon.EvolvesInto == null ? "No evolutions" : string.Join(", ", requestedPokémon.EvolvesInto) }); builder.Fields.Add(new EmbedFieldBuilder { IsInline = false, Name = "Types", Value = requestedPokémon.Types == null ? "Error" : string.Join(", ", requestedPokémon.Types) }); builder.Fields.Add(new EmbedFieldBuilder { IsInline = true, Name = "Size", Value = requestedPokémon.Height }); builder.Fields.Add(new EmbedFieldBuilder { IsInline = true, Name = "Mass", Value = requestedPokémon.Weight }); builder.Fields.Add(new EmbedFieldBuilder { IsInline = true, Name = "Egg Groups", Value = $"{requestedPokémon.EggGroups.EggGroup1}{(requestedPokémon.EggGroups.EggGroup2 == null ? string.Empty : "\n" + requestedPokémon.EggGroups.EggGroup2)}" }); builder.Fields.Add(new EmbedFieldBuilder { IsInline = false, Name = "Base stats", Value = $"HP: {requestedPokémon.BaseStats.Hp} ATK: {requestedPokémon.BaseStats.Attack} DEF: {requestedPokémon.BaseStats.Defense} SPATK: {requestedPokémon.BaseStats.SpecialAttack} SPDEF: {requestedPokémon.BaseStats.SpecialDefense} SPE: {requestedPokémon.BaseStats.Speed}" }); builder.Fields.Add(new EmbedFieldBuilder { IsInline = true, Name = "Abilities", Value = $"{requestedPokémon.Abilities.Ability1}{(requestedPokémon.Abilities.Ability2 == requestedPokémon.Abilities.Ability1 || requestedPokémon.Abilities.Ability2 == null ? string.Empty : $"; {requestedPokémon.Abilities.Ability2}")}" }); if (requestedPokémon.Abilities.AbilityH != null) { builder.Fields.Add(new EmbedFieldBuilder { IsInline = true, Name = "Hidden Ability", Value = requestedPokémon.Abilities.AbilityH }); } await this.ReplyAsync(string.Empty, false, builder.Build()); /*SvnClient client = new SvnClient(); * client.Export(SvnTarget.FromString("https://github.com/Zarel/Pokemon-Showdown/trunk/master/data"), PathsHelper.CreateIfDoesNotExist(Program.AppPath, "Pokemon-Data")); * * * * string hostName = "localhost"; * * string cs = @"server=" + hostName + @";userid=jordan;database=pmu_data;password=JordantheBuizel;"; * * MySqlConnection conn = null; * * try * { * conn = new MySqlConnection(cs); * conn.Open(); * * string stm = "SELECT VERSION()"; * MySqlCommand cmd = new MySqlCommand(stm, conn); * string version = Convert.ToString(cmd.ExecuteScalar()); * Console.WriteLine("MySQL version : {0}", version); * } * catch * { * IUser jordan = await this.Context.Client.GetUserAsync(228019100008316948); * IDMChannel jordanDmChannel = await jordan.GetOrCreateDMChannelAsync(); * await jordanDmChannel.SendMessageAsync("SQL is down!"); * return; * } * * try * { * int dexNum = 0; * * string eggGroup1 = string.Empty; * * string eggGroup2 = string.Empty; * * bool validPoke = false; * * bool specificForm = pokeName.Contains("-") && * pokeName.Split('-')[1].Length > 3; * * pokeName = !specificForm * ? pokeName * : pokeName.Split('-')[0]; * * string formName = specificForm ? pokeName.Split('-')[1] : string.Empty; * * EmbedBuilder messageBuilder = new EmbedBuilder(); * * int hP = 0; * * int attack = 0; * * int defense = 0; * * int specialAttack = 0; * * int specialDefense = 0; * * int speed = 0; * * double height = 0; * * double weight = 0; * * List<string> abilities = new List<string>(); * * Program.PokemonType type1 = Program.PokemonType.None; * * Program.PokemonType type2 = Program.PokemonType.None; * * pokeName = pokeName.Replace("\'", "\'\'").Replace("\\", string.Empty); * formName = formName.Replace("\'", "\'\'").Replace("\\", string.Empty); * * pokeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(pokeName); * * List<string> forms = new List<string>(); * * MySqlCommand command = new MySqlCommand( * $"SELECT DexNum FROM `pokedex_pokemon` WHERE PokemonName = '{pokeName}'", * conn); * MySqlDataReader reader = command.ExecuteReader(); * * while (reader.Read()) * { * validPoke = reader.HasRows; * dexNum = reader.GetInt32("DexNum"); * } * * if (dexNum > 7000) * { * dexNum -= 7000; * } * * if (dexNum > 721 || dexNum <= 0) * { * await this.Context.Channel.SendMessageAsync("Pokémon not found!"); * return; * } * * reader.Close(); * * messageBuilder.Title = pokeName; * messageBuilder.Footer = new EmbedFooterBuilder().WithText($"#{dexNum}"); * * command = new MySqlCommand( * $"SELECT EggGroup1, EggGroup2 FROM `pokedex_pokemon` WHERE PokemonName = '{pokeName}'", * conn); * reader = command.ExecuteReader(); * * while (reader.Read()) * { * eggGroup1 = reader.GetString("EggGroup1"); * eggGroup2 = reader.GetString("EggGroup2"); * } * * reader.Close(); * * command = new MySqlCommand( * $"SELECT EggGroup1, EggGroup2 FROM `pokedex_pokemon` WHERE PokemonName = '{pokeName}'", * conn); * reader = command.ExecuteReader(); * * while (reader.Read()) * { * eggGroup1 = reader.GetString("EggGroup1"); * eggGroup2 = reader.GetString("EggGroup2"); * } * * reader.Close(); * * if (!eggGroup2.Contains("Undiscovered")) * { * eggGroup2 = ", " + eggGroup2; * } * else * { * eggGroup2 = string.Empty; * } * * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = $"Egg Groups:", * Value = $"{eggGroup1}{eggGroup2}", * IsInline = false * }); * * if (!specificForm) * { * command = new MySqlCommand( * $"SELECT FormName FROM `pokedex_pokemonform` WHERE DexNum = '{dexNum}'", conn); * reader = command.ExecuteReader(); * * while (reader.Read()) * { * forms.Add(reader.GetString("FormName")); * } * * reader.Close(); * * List<string> distinctForms = forms.Distinct().ToList(); * * if (distinctForms.Count > 1) * { * string formsBuilder = string.Empty; * * foreach (string form in distinctForms) * { * formsBuilder += " " + pokeName + "-" + form; * } * * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Other forms:", * Value = formsBuilder, * IsInline = true * }); * } * * command = new MySqlCommand( * $"SELECT HP, Attack, Defense, SpecialAttack, SpecialDefense, Speed, Height, Weight, Type1, Type2, Ability1, Ability2, Ability3 FROM `pokedex_pokemonform` WHERE DexNum = '{dexNum}' AND FormName = 'Normal'", * conn); * reader = command.ExecuteReader(); * * while (reader.Read()) * { * hP = reader.GetInt32("HP"); * attack = reader.GetInt32("Attack"); * defense = reader.GetInt32("Defense"); * specialAttack = reader.GetInt32("SpecialAttack"); * specialDefense = reader.GetInt32("SpecialDefense"); * speed = reader.GetInt32("Speed"); * height = reader.GetDouble("Height"); * weight = reader.GetDouble("Weight"); * type1 = (Program.PokemonType)reader.GetInt32("Type1"); * type2 = (Program.PokemonType)reader.GetInt32("Type2"); * abilities.Add(reader.GetString("Ability1")); * abilities.Add(reader.GetString("Ability2")); * abilities.Add(reader.GetString("Ability3")); * } * * reader.Close(); * * List<string> distinctAbilities = abilities.Distinct().ToList(); * distinctAbilities.RemoveAll(e => e.Contains("None")); * * messageBuilder.Fields.Add(new EmbedFieldBuilder().WithName("\nAbilities: ").WithIsInline(false)); * * if (distinctAbilities.Count == 1) * { * messageBuilder.Fields.Last().Value += distinctAbilities[0]; * } * else * { * foreach (string ability in abilities) * { * if (!((string)messageBuilder.Fields.Last().Value).Contains(ability) && ability != "None") * { * messageBuilder.Fields.Last().Value += ability + ", "; * } * } * * messageBuilder.Fields.Last().Value = ((string)messageBuilder.Fields.Last().Value).TrimEnd(' ', ','); * } * * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Base stats:", * Value = $"{hP}/{attack}/{defense}/{specialAttack}/{specialDefense}/{speed}", * IsInline = false * }); * * if (type2 != Program.PokemonType.None) * { * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Types:", * Value = $"{Enum.GetName(typeof(Program.PokemonType), type1)}, {Enum.GetName(typeof(Program.PokemonType), type2)}", * IsInline = false * }); * } * else * { * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Types:", * Value = $"{Enum.GetName(typeof(Program.PokemonType), type1)}", * IsInline = false * }); * } * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Height:", * Value = $"{height}", * IsInline = false * }); * * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Weight:", * Value = $"{weight}", * IsInline = true * }); * * await this.StopTyping(); * * await this.Context.Channel.SendMessageAsync(string.Empty, false, messageBuilder.Build()); * } * else * { * command = new MySqlCommand( * $"SELECT HP, Attack, Defense, SpecialAttack, SpecialDefense, Speed, Height, Weight, Type1, Type2, Ability1, Ability2, Ability3 FROM `pokedex_pokemonform` WHERE DexNum = '{dexNum}' AND FormName = '{formName}'", * conn); * reader = command.ExecuteReader(); * * while (reader.Read()) * { * hP = reader.GetInt32("HP"); * attack = reader.GetInt32("Attack"); * defense = reader.GetInt32("Defense"); * specialAttack = reader.GetInt32("SpecialAttack"); * specialDefense = reader.GetInt32("SpecialDefense"); * speed = reader.GetInt32("Speed"); * height = reader.GetDouble("Height"); * weight = reader.GetDouble("Weight"); * type1 = (Program.PokemonType)reader.GetInt32("Type1"); * type2 = (Program.PokemonType)reader.GetInt32("Type2"); * abilities.Add(reader.GetString("Ability1")); * abilities.Add(reader.GetString("Ability2")); * abilities.Add(reader.GetString("Ability3")); * } * * reader.Close(); * * List<string> distinctAbilities = abilities.Distinct().ToList(); * distinctAbilities.RemoveAll(e => e.Contains("None")); * * messageBuilder.Fields.Add(new EmbedFieldBuilder().WithName("\nAbilities: ").WithIsInline(false)); * * if (distinctAbilities.Count == 1) * { * messageBuilder.Fields.Last().Value += distinctAbilities[0]; * } * else * { * foreach (string ability in abilities) * { * if (!((string)messageBuilder.Fields.Last().Value).Contains(ability) && ability != "None") * { * messageBuilder.Fields.Last().Value += ability + ", "; * } * } * * messageBuilder.Fields.Last().Value = ((string)messageBuilder.Fields.Last().Value).TrimEnd(' ', ','); * } * * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Base stats:", * Value = $"{hP}/{attack}/{defense}/{specialAttack}/{specialDefense}/{speed}", * IsInline = false * }); * * if (type2 != Program.PokemonType.None) * { * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Types:", * Value = $"{Enum.GetName(typeof(Program.PokemonType), type1)}, {Enum.GetName(typeof(Program.PokemonType), type2)}", * IsInline = false * }); * } * else * { * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Types:", * Value = $"{Enum.GetName(typeof(Program.PokemonType), type1)}", * IsInline = false * }); * } * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Height:", * Value = $"{height}", * IsInline = false * }); * * messageBuilder.Fields.Add(new EmbedFieldBuilder * { * Name = "Weight:", * Value = $"{weight}", * IsInline = true * }); * * await this.StopTyping(); * * await this.Context.Channel.SendMessageAsync(string.Empty, false, messageBuilder.Build()); * } * } * catch (Exception ex) * { * Console.Out.WriteLine($"Error \n {ex.Message} \n {ex.StackTrace} \n {ex.Source}"); * }*/ }
private List <PokémonAPI.Type> GetTypes(Pokémon p) { return(p.Types); }
private List <Move> GetMoves(Pokémon p) { return(p.Moves); }