Beispiel #1
0
 internal PBETeams(PBEBattle battle, PBETeamShell team1Shell, string team1TrainerName, PBETeamShell team2Shell, string team2TrainerName)
 {
     _team1 = new PBETeam(battle, 0, team1Shell, team1TrainerName);
     _team2 = new PBETeam(battle, 1, team2Shell, team2TrainerName);
     _team1.OpposingTeam = _team2;
     _team2.OpposingTeam = _team1;
 }
Beispiel #2
0
 internal PBETeam(PBEBattle battle, byte id, PBETeamShell shell, string trainerName)
 {
     Battle = battle;
     Id     = id;
     Party  = new PBEList <PBEPokemon>(Battle.Settings.MaxPartySize);
     CreateParty(shell, trainerName);
 }
Beispiel #3
0
 public void PartySubmitted(Player player, PBETeamShell teamShell)
 {
     if (_state != ServerState.WaitingForParties)
     {
         return;
     }
     lock (this)
     {
         if (_state != ServerState.WaitingForParties)
         {
             return;
         }
         foreach (PBEPokemonShell shell in teamShell)
         {
             try
             {
                 // Not currently necessary, but it would be necessary eventually because PBEMovesetBuilder cannot check if a moveset "makes sense" for the method the Pokémon was obtained in
                 // Eventually we would probably want to store that sort of information in PBEPokemonShell
                 PBELegalityChecker.MoveLegalityCheck(shell.Moveset);
             }
             catch (Exception e)
             {
                 Console.WriteLine($"Illegal moveset received from {player.TrainerName}");
                 Console.WriteLine(e.Message);
                 CancelMatch();
                 return;
             }
         }
         PBEBattle.CreateTeamParty(_battle.Teams[player.BattleId], teamShell, player.TrainerName);
     }
 }
            public async Task Challenge(SocketUser battler1)
            {
                if (battler1.Id == Context.User.Id)
                {
                    //
                }
                else if (BattleContext.GetBattleContext(Context.User) != null)
                {
                    await Context.Channel.SendMessageAsync($"{Context.User.Username} is already participating in a battle.");
                }
                else if (BattleContext.GetBattleContext(battler1) != null)
                {
                    await Context.Channel.SendMessageAsync($"{battler1.Username} is already participating in a battle.");
                }
                else
                {
                    PBETeamShell team1Shell, team2Shell;
                    // Completely Randomized Pokémon
                    team1Shell = new PBETeamShell(PBESettings.DefaultSettings, PBESettings.DefaultMaxPartySize, true);
                    team2Shell = new PBETeamShell(PBESettings.DefaultSettings, PBESettings.DefaultMaxPartySize, true);

                    var battle = new PBEBattle(PBEBattleFormat.Single, team1Shell, Context.User.Username, team2Shell, battler1.Username);
                    new BattleContext(battle, Context.User, battler1, Context.Channel);
                }
            }
Beispiel #5
0
 internal void CreateParty(PBETeamShell shell, string trainerName)
 {
     TrainerName = trainerName;
     for (int i = 0; i < shell.Count; i++)
     {
         new PBEPokemon(this, (byte)((Id * Battle.Settings.MaxPartySize) + i), shell[i]);
     }
 }
Beispiel #6
0
 public NetworkClient(PBEBattleFormat battleFormat, PBETeamShell teamShell)
     : base(new PBEBattle(battleFormat, teamShell.Settings), ClientMode.Online)
 {
     _teamShell = teamShell;
     _client    = new PBEClient {
         Battle = Battle
     };
     _client.Disconnected   += OnDisconnected;
     _client.Error          += OnError;
     _client.PacketReceived += OnPacketReceived;
 }
        public PBEPartyResponsePacket(PBETeamShell teamShell)
        {
            if (teamShell == null)
            {
                throw new ArgumentNullException(nameof(teamShell));
            }
            var bytes = new List <byte>();

            bytes.AddRange(BitConverter.GetBytes(Code));
            (TeamShell = teamShell).ToBytes(bytes);
            bytes.InsertRange(0, BitConverter.GetBytes((short)bytes.Count));
            Buffer = new ReadOnlyCollection <byte>(bytes);
        }
 public PBEPartyResponsePacket(PBETeamShell teamShell)
 {
     if (teamShell == null)
     {
         throw new ArgumentNullException(nameof(teamShell));
     }
     using (var ms = new MemoryStream())
         using (var w = new EndianBinaryWriter(ms, encoding: EncodingType.UTF16))
         {
             w.Write(Code);
             (TeamShell = teamShell).ToBytes(w);
             Data = new ReadOnlyCollection <byte>(ms.ToArray());
         }
 }
 public SinglePlayerClient(PBEBattleFormat battleFormat, PBETeamShell team1Shell, string team1TrainerName, PBETeamShell team2Shell, string team2TrainerName)
     : base(new PBEBattle(battleFormat, team1Shell, team1TrainerName, team2Shell, team2TrainerName), ClientMode.SinglePlayer)
 {
     BattleId               = 0;
     Team                   = Battle.Teams[0];
     ShowRawValues0         = true;
     ShowRawValues1         = false;
     Battle.OnNewEvent     += SinglePlayerBattle_OnNewEvent;
     Battle.OnStateChanged += SinglePlayerBattle_OnStateChanged;
     new Thread(Battle.Begin)
     {
         Name = "Battle Thread"
     }.Start();
 }
Beispiel #10
0
        public override void HandleMessage(INetPacket packet)
        {
            Debug.WriteLine($"Message received: \"{packet.GetType().Name}\" ({BattleId})");
            if (Socket == null || ResetEvent.SafeWaitHandle.IsClosed)
            {
                return;
            }
            ResetEvent.Set();

            if (BattleId < 2)
            {
                var ser = (BattleServer)Server;
                switch (packet)
                {
                case PBEActionsResponsePacket arp:
                {
                    ser.ActionsSubmitted(this, arp.Actions);
                    break;
                }

                case PBEPartyResponsePacket prp:
                {
                    Console.WriteLine($"Received team from {TrainerName}!");
                    if (TeamShell == null)
                    {
                        TeamShell = prp.TeamShell;
                        ser.PartySubmitted(this);
                    }
                    else
                    {
                        Console.WriteLine("Team submitted multiple times!");
                    }
                    break;
                }

                case PBESwitchInResponsePacket sirp:
                {
                    ser.SwitchesSubmitted(this, sirp.Switches);
                    break;
                }
                }
            }
        }
Beispiel #11
0
        private void OnPacketReceived(object sender, IPBEPacket packet)
        {
            Debug.WriteLine($"Packet received ({BattleId} \"{packet.GetType().Name}\")");
            resetEvent.Set();
            if (BattleId < 2)
            {
                switch (packet)
                {
                case PBEActionsResponsePacket arp:
                {
                    Server.ActionsSubmitted(this, arp.Actions);
                    break;
                }

                case PBEPartyResponsePacket prp:
                {
                    Console.WriteLine($"Received team from {TrainerName}!");
                    if (!submittedTeam)
                    {
                        submittedTeam = true;
                        PBETeamShell s = prp.TeamShell;
                        Server.PartySubmitted(this, s);
                        s.Dispose();
                    }
                    else
                    {
                        Console.WriteLine("Team submitted multiple times!");
                    }
                    break;
                }

                case PBESwitchInResponsePacket sirp:
                {
                    Server.SwitchesSubmitted(this, sirp.Switches);
                    break;
                }
                }
            }
            // TODO: Kick players who are sending bogus packets or sending too many
        }
Beispiel #12
0
 /// <summary>Creates a new <see cref="PBEBattle"/> object with the specified <see cref="PBEBattleFormat"/> and teams. Each team must have equal settings. The battle's settings are set to a copy of the teams' settings. <see cref="BattleState"/> will be <see cref="PBEBattleState.ReadyToBegin"/>.</summary>
 /// <param name="battleFormat">The <see cref="PBEBattleFormat"/> of the battle.</param>
 /// <param name="team1Shell">The <see cref="PBETeamShell"/> object to use to create <see cref="Teams"/>[0].</param>
 /// <param name="team1TrainerName">The name of the trainer(s) on <see cref="Teams"/>[0].</param>
 /// <param name="team2Shell">The <see cref="PBETeamShell"/> object to use to create <see cref="Teams"/>[1].</param>
 /// <param name="team2TrainerName">The name of the trainer(s) on <see cref="Teams"/>[1].</param>
 /// <exception cref="ArgumentNullException">Thrown when <paramref name="team1Shell"/> or <paramref name="team2Shell"/> are null.</exception>
 /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="team1Shell"/> and <paramref name="team2Shell"/> have unequal <see cref="PBETeamShell.Settings"/> or when <paramref name="team1TrainerName"/> or <paramref name="team2TrainerName"/> are invalid.</exception>
 public PBEBattle(PBEBattleFormat battleFormat, PBETeamShell team1Shell, string team1TrainerName, PBETeamShell team2Shell, string team2TrainerName)
 {
     if (battleFormat >= PBEBattleFormat.MAX)
     {
         throw new ArgumentOutOfRangeException(nameof(battleFormat));
     }
     if (team1Shell == null)
     {
         throw new ArgumentNullException(nameof(team1Shell));
     }
     if (team2Shell == null)
     {
         throw new ArgumentNullException(nameof(team2Shell));
     }
     if (string.IsNullOrWhiteSpace(team1TrainerName))
     {
         throw new ArgumentOutOfRangeException(nameof(team1TrainerName));
     }
     if (string.IsNullOrWhiteSpace(team2TrainerName))
     {
         throw new ArgumentOutOfRangeException(nameof(team2TrainerName));
     }
     if (team1Shell.IsDisposed)
     {
         throw new ObjectDisposedException(nameof(team1Shell));
     }
     if (team2Shell.IsDisposed)
     {
         throw new ObjectDisposedException(nameof(team2Shell));
     }
     if (!team1Shell.Settings.Equals(team2Shell.Settings))
     {
         throw new ArgumentOutOfRangeException(nameof(team1Shell.Settings), "Team settings must be equal to each other.");
     }
     BattleFormat = battleFormat;
     Settings     = new PBESettings(team1Shell.Settings);
     Settings.MakeReadOnly();
     Teams = new PBETeams(this, team1Shell, team1TrainerName, team2Shell, team2TrainerName);
     CheckForReadiness();
 }
Beispiel #13
0
 /// <summary>Sets a specific team's party. <see cref="BattleState"/> will change to <see cref="PBEBattleState.ReadyToBegin"/> if all teams have parties.</summary>
 /// <param name="team">The team which will have its party set.</param>
 /// <param name="teamShell">The information <paramref name="team"/> will use to create its party.</param>
 /// <param name="teamTrainerName">The name of the trainer(s) on <paramref name="team"/>.</param>
 /// <exception cref="InvalidOperationException">Thrown when <see cref="BattleState"/> is not <see cref="PBEBattleState.WaitingForPlayers"/> or <paramref name="team"/> already has its party set.</exception>
 /// <exception cref="ArgumentNullException">Thrown when <paramref name="team"/> or <paramref name="teamShell"/> is null.</exception>
 /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="teamShell"/>'s settings are unequal to <paramref name="team"/>'s battle's settings or when <paramref name="teamTrainerName"/> is invalid.</exception>
 public static void CreateTeamParty(PBETeam team, PBETeamShell teamShell, string teamTrainerName)
 {
     if (team == null)
     {
         throw new ArgumentNullException(nameof(team));
     }
     if (teamShell == null)
     {
         throw new ArgumentNullException(nameof(teamShell));
     }
     if (string.IsNullOrEmpty(teamTrainerName))
     {
         throw new ArgumentOutOfRangeException(nameof(teamTrainerName));
     }
     if (team.IsDisposed)
     {
         throw new ObjectDisposedException(nameof(team));
     }
     if (teamShell.IsDisposed)
     {
         throw new ObjectDisposedException(nameof(teamShell));
     }
     if (!teamShell.Settings.Equals(team.Battle.Settings))
     {
         throw new ArgumentOutOfRangeException(nameof(teamShell), $"\"{nameof(teamShell)}\"'s settings must be equal to the battle's settings.");
     }
     if (team.Battle.BattleState != PBEBattleState.WaitingForPlayers)
     {
         throw new InvalidOperationException($"{nameof(BattleState)} must be {PBEBattleState.WaitingForPlayers} to set a team's party.");
     }
     if (team.Party.Count > 0)
     {
         throw new InvalidOperationException("This team already has its party set.");
     }
     team.CreateParty(teamShell, teamTrainerName);
     team.Battle.CheckForReadiness();
 }
Beispiel #14
0
 internal TeamInfo(string name, PBETeamShell shell)
 {
     Name  = name;
     Shell = shell;
 }
        public static void Run()
        {
            Console.WriteLine("----- Pokémon Battle Engine - AI Battle Demo -----");
            try
            {
                _writer = new StreamWriter(new FileStream(LogFile, FileMode.Create, FileAccess.Write));
            }
            catch (Exception e)
            {
                Console.WriteLine($"Cannot open \"{LogFile}\" for writing.");
                Console.WriteLine(e.Message);
                return;
            }

            var settings = new PBESettings {
                NumMoves = 8, MaxPartySize = 10
            };
            PBETeamShell team1Shell, team2Shell;

            // Completely Randomized Pokémon
            team1Shell = new PBETeamShell(settings, settings.MaxPartySize, true);
            team2Shell = new PBETeamShell(settings, settings.MaxPartySize, true);

            // Predefined Pokémon

            /*team0Shell = new PBEPokemonShell[]
             * {
             *  PBECompetitivePokemonShells.Zoroark_VGC,
             *  PBECompetitivePokemonShells.Volcarona_VGC,
             *  PBECompetitivePokemonShells.Vaporeon_VGC,
             *  PBECompetitivePokemonShells.Thundurus_VGC,
             *  PBECompetitivePokemonShells.Vanilluxe_VGC,
             *  PBECompetitivePokemonShells.Chandelure_VGC
             * };
             * team1Shell = new PBEPokemonShell[]
             * {
             *  PBECompetitivePokemonShells.Arceus_Uber,
             *  PBECompetitivePokemonShells.Darkrai_Uber,
             *  PBECompetitivePokemonShells.Kyurem_White_Uber,
             *  PBECompetitivePokemonShells.Latias_VGC,
             *  PBECompetitivePokemonShells.Metagross_VGC,
             *  PBECompetitivePokemonShells.Victini_Uber
             * };*/

            _battle                 = new PBEBattle(PBEBattleFormat.Double, team1Shell, "Team 1", team2Shell, "Team 2");
            _battle.OnNewEvent     += PBEBattle.ConsoleBattleEventHandler;
            _battle.OnNewEvent     += Battle_OnNewEvent;
            _battle.OnStateChanged += Battle_OnStateChanged;
            _oldWriter              = Console.Out;
            Console.SetOut(_writer);
            new Thread(() =>
            {
                try
                {
                    _battle.Begin();
                }
                catch (Exception e)
                {
                    CatchException(e);
                }
            })
            {
                Name = "Battle Thread"
            }.Start();
        }
 internal PBEPartyResponsePacket(ReadOnlyCollection <byte> buffer, BinaryReader r, PBEBattle battle)
 {
     Buffer    = buffer;
     TeamShell = new PBETeamShell(battle.Settings, r); // What happens if an exception occurs? Similar question to https://github.com/Kermalis/PokemonBattleEngine/issues/167
 }
 internal PBEPartyResponsePacket(byte[] data, EndianBinaryReader r, PBEBattle battle)
 {
     Data      = new ReadOnlyCollection <byte>(data);
     TeamShell = new PBETeamShell(battle.Settings, r);
 }
Beispiel #18
0
        public void Basic_Actions_Checks()
        {
            PBEUtils.CreateDatabaseConnection(string.Empty);
            PBESettings settings = PBESettings.DefaultSettings;

            var             team1Shell = new PBETeamShell(settings, 2, true);
            PBEPokemonShell p          = team1Shell[0];

            p.Species         = PBESpecies.Koffing;
            p.Item            = PBEItem.None;
            p.Moveset[0].Move = PBEMove.Selfdestruct;

            var team2Shell = new PBETeamShell(settings, 1, true);

            p                 = team2Shell[0];
            p.Species         = PBESpecies.Darkrai;
            p.Item            = PBEItem.None;
            p.Moveset[0].Move = PBEMove.Protect;

            var battle = new PBEBattle(PBEBattleFormat.Single, team1Shell, "Team 1", team2Shell, "Team 2");

            team1Shell.Dispose();
            team2Shell.Dispose();
            battle.Begin();

            PBETeam t  = battle.Teams[0];
            var     a  = new PBETurnAction(t.Party[0].Id, PBEMove.Selfdestruct, PBETurnTarget.FoeCenter);
            var     a1 = new PBETurnAction[] { a };

            Assert.Throws <ArgumentNullException>(() => PBEBattle.SelectActionsIfValid(null, a1));                        // Throw for null team
            Assert.Throws <ArgumentNullException>(() => PBEBattle.SelectActionsIfValid(t, null));                         // Throw for null collection
            Assert.Throws <ArgumentNullException>(() => PBEBattle.SelectActionsIfValid(t, new PBETurnAction[] { null })); // Throw for null elements
            Assert.False(PBEBattle.SelectActionsIfValid(t, new PBETurnAction[] { a, a }));                                // False for too many actions
            Assert.True(PBEBattle.SelectActionsIfValid(t, a1));                                                           // True for good actions
            // TODO: bad move, bad targets, bad targets with templockedmove, battle status, bad pkmn id, wrong team pkmn id, duplicate pkmn id, can't switch out but tried, invalid switch mon (null hp pos), duplicate switch mon
            Assert.False(PBEBattle.SelectActionsIfValid(t, a1));                                                          // False because actions were already submitted
            Assert.False(PBEBattle.SelectActionsIfValid(t, Array.Empty <PBETurnAction>()));                               // False for 0 despite us now needing 0 additional actions

            t = battle.Teams[1];
            Assert.True(PBEBattle.SelectActionsIfValid(t, new PBETurnAction[] { new PBETurnAction(t.Party[0].Id, PBEMove.Protect, PBETurnTarget.AllyCenter) })); // True for good actions

            battle.RunTurn();                                                                                                                                    // Darkrai uses Protect, Koffing uses Selfdestruct, Koffing faints

            t = battle.Teams[0];
            var s  = new PBESwitchIn(t.Party[1].Id, PBEFieldPosition.Center);
            var s1 = new PBESwitchIn[] { s };

            Assert.Throws <ArgumentNullException>(() => PBEBattle.SelectSwitchesIfValid(null, s1));                      // Throw for null team
            Assert.Throws <ArgumentNullException>(() => PBEBattle.SelectSwitchesIfValid(t, null));                       // Throw for null collection
            Assert.Throws <ArgumentNullException>(() => PBEBattle.SelectSwitchesIfValid(t, new PBESwitchIn[] { null })); // Throw for null elements
            Assert.False(PBEBattle.SelectSwitchesIfValid(t, new PBESwitchIn[] { s, s }));                                // False for too many
            Assert.True(PBEBattle.SelectSwitchesIfValid(t, s1));                                                         // True for good switches
            // Below two wouldn't work because of battle status lol
            //Assert.False(PBEBattle.SelectSwitchesIfValid(t, s1)); // False because switches were already submitted
            //Assert.False(PBEBattle.SelectSwitchesIfValid(t, Array.Empty<PBESwitchIn>())); // False for 0 despite us now needing 0 additional actions

            battle.Dispose();

            Assert.Throws <ObjectDisposedException>(() => PBEBattle.SelectActionsIfValid(t, a1));  // Throw for disposed battle
            Assert.Throws <ObjectDisposedException>(() => PBEBattle.SelectSwitchesIfValid(t, s1)); // Throw for disposed battle
        }