public bool CanSpawnMoreBots(MyPlayer.PlayerId pid)
        {
            if (!Sync.IsServer)
            {
                Debug.Assert(false, "Server only");
                return(false);
            }

            int perPlayerBotMultiplier = (MySession.Static.CreativeMode ? MySession.Static.MaxPlayers : 1);

            if (MySteam.UserId == pid.SteamId)
            {
                AgentSpawnData spawnData = default(AgentSpawnData);
                if (m_agentsToSpawn.TryGetValue(pid.SerialId, out spawnData))
                {
                    if (spawnData.CreatedByPlayer)
                    {
                        return(Bots.GetCreatedBotCount() < BotFactory.MaximumBotPerPlayer * perPlayerBotMultiplier);
                    }
                    else
                    {
                        return(Bots.GetGeneratedBotCount() < BotFactory.MaximumUncontrolledBotCount);
                    }
                }
                else
                {
                    Debug.Assert(false, "Bot doesn't exist");
                    return(false);
                }
            }
            else
            {
                int botCount     = 0;
                var lookedPlayer = pid.SteamId;
                var players      = Sync.Players.GetAllPlayers();

                if (MySession.Static.CreativeMode)
                {
                    foreach (var player in players)
                    {
                        if (player.SerialId != 0)
                        {
                            ++botCount;
                        }
                    }
                }
                else
                {
                    foreach (var player in players)
                    {
                        if (player.SteamId == lookedPlayer && player.SerialId != 0)
                        {
                            botCount++;
                        }
                    }
                }

                return(botCount < BotFactory.MaximumBotPerPlayer * perPlayerBotMultiplier);
            }
        }
示例#2
0
        public override async Task UpdateAsync()
        {
            await base.UpdateAsync();

            ElapsedTime += DeltaTime;
            if (Battlefield.Resources.Count < myResourceCount)
            {
                AddResource();
            }
            if (Battlefield.Weapons.Count < myWeaponsCount)
            {
                AddWeapon();
            }
            if (Battlefield.FirstAidKits.Count < myFirstAidKitCount)
            {
                AddFirstAidKit();
            }
            var bulletTasks = Battlefield.Bullets.ToList()
                              .OfType <Bullet>().Select(b => b.UpdateAsync());
            await Task.WhenAll(bulletTasks);

            var botTasks = Bots.Select(b => b.UpdateAsync());
            await Task.WhenAll(botTasks);

            var hospitalTasks = Battlefield.Hospitals.ToList()
                                .OfType <Hospital>().Select(b => b.UpdateAsync());
            await Task.WhenAll(hospitalTasks);

            var explosionTasks = Battlefield.Explosions.ToList()
                                 .OfType <Explosion>().Select(b => b.UpdateAsync());
            await Task.WhenAll(explosionTasks);

            await Task.Delay(TimeSpan.FromMilliseconds(myTurnDelay));
        }
示例#3
0
        /// <summary>
        /// Changes the bot.
        /// </summary>
        /// <param name="file">The file.</param>
        private static void ChangeBot(string file)
        {
            try
            {
                var settings = SettingsManager.LoadSettings(file);
                var bot      = Bots[settings];

                if (bot == default(BotInstance))
                {
                    Bots.Add(new BotInstance(settings));
                }
                else
                {
                    bot.ChangeSettings(settings);
                }

                Queue.Remove(file);
            }
            catch (InvalidOperationException ex)
            {
                LogService.Warning(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
                Queue.Add(file);
            }
            catch (IOException ex)
            {
                LogService.Warning(string.Format("{0} File will be queued for later reading.", ex.Message));
                Queue.Add(file);
            }
            catch (Exception ex)
            {
                LogService.Warning(ex.ToString());
            }
        }
示例#4
0
            public SimObject AddOrGetObject(string name)
            {
                SimObject obj;

                if (Objects.ContainsKey(name))
                {
                    obj = Objects[name];
                }
                else
                {
                    if (name.StartsWith("bot"))
                    {
                        obj = new Bot(this, name);
                        Bots.Add(obj as Bot);
                    }
                    else if (name.StartsWith("output"))
                    {
                        obj = new Output(this, name);
                        Outputs.Add(obj as Output);
                    }
                    else
                    {
                        throw new ArgumentException("unknown name");
                    }
                    Objects[name] = obj;
                }
                return(obj);
            }
示例#5
0
        private void RunGeneration()
        {
            StatusMonitor.BotsAliveCount = Config.GenerationSize;
            while (StatusMonitor.BotsAliveCount > Config.ParentsCount)
            {
                if (++StatusMonitor.GenerationIterationNumber >= Config.GenIterationsCountGoal)
                {
                    break;
                }
                foreach (var bot in Bots.Where(bot => !bot.IsDead))
                {
                    PerformBotAction(bot);
                    if (state.Name == EmulationStateName.PendedToRestart)
                    {
                        return;
                    }
                    if (StatusMonitor.BotsAliveCount <= Config.ParentsCount)
                    {
                        break;
                    }
                }

                SpawnItem(WorldObjectType.Food);
                SpawnItem(WorldObjectType.Poison);
                GenIterationPerformed?.Invoke();
                if (Config.DelayType == DelayTypes.PerEachGenIteration)
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(Config.IterationDelayMilliseconds));
                }
            }
            StatusMonitor.GenIterationsStatistics.Add(StatusMonitor.GenerationIterationNumber);
            GenerationRunEnded?.Invoke();
        }
示例#6
0
        // fire off a game with selected parameters
        async void StartGame()
        {
            // check if two bots picked
            // check if map picked

            var p1 = Bots.Where(b => b.Player1).FirstOrDefault();
            var p2 = Bots.Where(b => b.Player2).FirstOrDefault();

            if (p1 == null || p2 == null)
            {
                // sageBox.Show("Select player 1 and 2");
                return;
            }

            LoadBackground();
            frameQueue = new ConcurrentQueue <FrameInfo>(); // erase old one
            var queue = frameQueue;                         // use local to avoid some background thread problems - todo - better to cancel and check cancel took, but more complicated

            Frame           = 0;
            planetDiameters = null;
            while (queue.TryDequeue(out var s))
            { // nothing
            }
            History.Clear();

            var dispatcher = Dispatcher.CurrentDispatcher;

            var res = await Task.Factory.StartNew(() =>
            {
                return(GameRunner.PlayOneGame(p1.player, p2.player, RandomSeed, queue.Enqueue, FrameMax));
            });
        }
示例#7
0
 public void CmdWait(int bid)
 {
     if (!Bots.ContainsKey(bid))
     {
         throw new CommandException("wait", "bot does not exist");
     }
 }
示例#8
0
        protected void LoadBots()
        {
            if (!SubPackages.Any(p => p.Name == "Bots"))
            {
                SayInfoLine("Loading Bots...");
                Controller.StartBeeper();
                var bots = new Bots(this.Controller);
                Controller.StopBeeper();
                if (bots.Initialized)
                {
                    SubPackages.Add(new Bots(this.Controller));
                }
                else
                {
                    SayErrorLine("The Bots package failed to initialize.");
                    return;
                }
            }
            Controller.ActivePackage = SubPackages.Single(p => p.Name == "Bots");

            if (CurrentContext.StartsWith("MENU_"))
            {
                DispatchIntent(null, Controller.ActivePackage.Menu);
            }
            else
            {
                DispatchIntent(null, Controller.ActivePackage.Menu);
            }
        }
示例#9
0
        /// <summary>
        /// Called from the Arena, when a bot calls the Arena.Cannon() method
        ///
        /// The Cannon() function fires a missile heading a specified range and direction.
        /// Cannon() returns 1 (true) if a missile was fired, or 0 (false) if the cannon is reloading.
        /// Degree is forced into the range 0-359 as in Scan() and Drive().
        /// Range can be 0-700, with greater ranges truncated to 700.
        ///
        /// Examples:
        ///    degree = 45;                              // set a direction to test
        ///    if ((range=Scan(robot, degree, 2)) > 0)   // see if a target is there
        ///      Cannon(robot, degree, range);           // fire a missile
        /// </summary>
        /// <param name="robot"></param>
        /// <param name="degree"></param>
        /// <param name="range"></param>
        /// <returns></returns>
        public bool FireCannon(Robot robot, int degree, int range)
        {
            degree = Arena.DegreeTo360(degree);
            if (range < 0)
            {
                range = 0;
            }
            if (range > 700)
            {
                range = 700;
            }

            BotAssembly bot = Bots.Find(botAssembly => botAssembly.Id == robot.Id);

            if (bot.MissilesInFlight < MaxMissles)
            {
                bot.MissilesInFlight++;
                Missiles.Add(new Missile
                {
                    Id       = robot.Id,
                    Speed    = 100,
                    Location = new PointF {
                        X = bot.Location.X, Y = bot.Location.Y
                    },
                    Direction = degree,
                    Range     = range
                });

                return(true);
            }

            return(false);
        }
示例#10
0
        /// <summary>
        /// Finalizes the instance.
        /// </summary>
        public void Flush()
        {
            // Set references to this object
            Compound.Instance = this;
            foreach (var instanceElement in
                     Bots.AsEnumerable <InstanceElement>()
                     .Concat(Pods.AsEnumerable <InstanceElement>())
                     .Concat(Elevators.AsEnumerable <InstanceElement>())
                     .Concat(InputStations.AsEnumerable <InstanceElement>())
                     .Concat(OutputStations.AsEnumerable <InstanceElement>())
                     .Concat(Waypoints.AsEnumerable <InstanceElement>())
                     .Concat(ItemDescriptions.AsEnumerable <InstanceElement>())
                     .Concat(ItemBundles.AsEnumerable <InstanceElement>()))
            {
                instanceElement.Instance = this;
            }

            //TODO:why is the code below commented out??

            //// Generate Waypointgraph
            //WaypointGraph = new WaypointGraph();
            //foreach (var waypoint in Waypoints)
            //{
            //    WaypointGraph.Add(waypoint);
            //}
        }
        static void Main(string[] args)
        {
            Console.Write("This programm represents the blackjack game with opportunity to split");
            Console.Write(" cards, double wagers and surrender.\n");
            Console.WriteLine("You can choose one of 3 strategies to play:");
            Console.WriteLine("0 - basic strategy");
            Console.WriteLine("1 - cards counting strategy, based on basic strategy and cards count");
            Console.WriteLine("2 - simple strategy, based on basic strategy and players score at the moment");
            Console.WriteLine("The programm will print the approximate sum of your wagers when the game ends");
            Console.WriteLine("Please enter the correct number of strategy you want to play");
            int strategy = Convert.ToInt32(Console.ReadLine()); // in ascii table "0" has 48 number

            if (strategy < 0 || strategy > 2)
            {
                Console.WriteLine("You number isn't right.");
                return;
            }
            Bots  botsStrategy = (Bots)strategy;
            Decks playingDecks = new Decks();

            playingDecks.FillCards();
            double        win  = 0;
            BlackjackGame game = new BlackjackGame(playingDecks, 1600, botsStrategy); // 1600 is initial players money

            for (int i = 0; i < 40; i++)
            {
                win += game.Game();
            }
            Console.WriteLine("Approximate sum with 40 played rounds is {0}", win / 40.0);
            Console.WriteLine("Press enter button to exit");
            Console.ReadLine();
        }
示例#12
0
        private async Task processBotRequest()
        {
            string requestPath = Constants.SERVER_PATH + Constants.GAME_JOIN_PATH;

            try
            {
                dynamic values = new JObject();
                values.username = SelectedBot;
                values.Add("isPrivate", false);
                values.lobbyName = this.LobbyName;
                values.password  = "";
                var content     = JsonConvert.SerializeObject(values);
                var buffer      = System.Text.Encoding.UTF8.GetBytes(content);
                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var response = await ServerService.instance.client.PostAsync(requestPath, byteContent);

                if (response.IsSuccessStatusCode)
                {
                    Bots.Remove(SelectedBot);
                }
                if (!response.IsSuccessStatusCode)
                {
                    var message = await response.Content.ReadAsStringAsync();

                    ErrorServerMessage serverMessage = JsonConvert.DeserializeObject <ErrorServerMessage>(message);
                    ShowMessageBox(serverMessage.message);
                }
            }
            catch (Exception e)
            {
                ShowMessageBox(e.Message);
            }
        }
示例#13
0
 private void refreshUserList(JObject data)
 {
     try
     {
         if ((string)data.GetValue("lobbyName") == this.LobbyName && ((string)data.GetValue("type") == "join"))
         {
             fetchUsername();
         }
         if ((string)data.GetValue("type") == "leave" && (string)data.GetValue("lobbyName") == this.LobbyName)
         {
             if (data.GetValue("username").ToString().Contains("bot:"))
             {
                 App.Current.Dispatcher.Invoke(delegate
                 {
                     Bots.Add(data.GetValue("username").ToString());
                 });
             }
             fetchUsername();
         }
     }
     catch (Exception e)
     {
         ShowMessageBox(e.Message);
     }
 }
示例#14
0
        public async Task StartAsync()
        {
            for (int i = 1; i <= Settings.MaxTurns; i++)
            {
                Turn = TurnFactory.Create(i);
                OnTurnStarting();
                await Turn.StartAsync(Bots);

                OnTurnFinished();
                if (Bots.Count(b => b.HP > 0) <= 1)
                {
                    break;
                }
                await WaitForNextTurnAsync();
            }

            var scores = new List <Score>();

            foreach (var bot in Bots)
            {
                scores.Add(new Score {
                    BotName = bot.Name, Kills = bot.Kills, Deaths = bot.Deaths
                });
            }
            Scores = scores;
        }
 public BlackjackGame(Decks playingDecks, uint initialMoney, Bots strategy)
 {
     PlayingCards      = new Decks();
     PlayingCards      = playingDecks;
     this.strategy     = strategy;
     this.initialMoney = initialMoney;
     PlayingDealer     = new Dealer(playingDecks, 0);
 }
示例#16
0
 /// <summary>
 /// Registers and returns a new ID for an object of the given type.
 /// </summary>
 /// <returns>A new unique ID that can be used to identify the object.</returns>
 public int RegisterBotID()
 {
     if (Bots.Any() && _botID <= Bots.Max(e => e.ID))
     {
         _botID = Bots.Max(e => e.ID) + 1;
     }
     return(_botID++);
 }
示例#17
0
 /// <summary>
 /// Remove all robots from the instance. This is only usable for visualization purposes.
 /// </summary>
 public void VisClearBots()
 {
     Bots.Clear();
     foreach (var tier in Compound.Tiers)
     {
         tier.Bots.Clear();
     }
 }
示例#18
0
 public int GetFreeTeamID(string exceptUser)
 {
     return
         (Enumerable.Range(0, TasClient.MaxTeams - 1).FirstOrDefault(
              teamID =>
              !Users.Where(u => !u.IsSpectator).Any(user => user.Name != exceptUser && user.TeamNumber == teamID) &&
              !Bots.Any(x => x.TeamNumber == teamID)));
 }
示例#19
0
        public void CmdFlip(int bid)
        {
            if (!Bots.ContainsKey(bid))
            {
                throw new CommandException("flip", "bot does not exist");
            }

            Harmonics = !Harmonics;
        }
示例#20
0
        public void CmdVoid(int bid, CoordinateDifference d)
        {
            if (!Bots.TryGetValue(bid, out var bot))
            {
                throw new CommandException("void", "bot does not exist");
            }

            Matrix.Get(bot.Position.X + d.X, bot.Position.Y + d.Y, bot.Position.Z + d.Z).Filled = false;
        }
示例#21
0
        public void CmdLmove(int bid, CoordinateDifference d1, CoordinateDifference d2)
        {
            if (!Bots.TryGetValue(bid, out var bot))
            {
                throw new CommandException("lmove", "bot does not exist");
            }

            bot.Position = Matrix.Get(bot.Position.X + d1.X + d2.X, bot.Position.Y + d1.Y + d2.Y, bot.Position.Z + d1.Z + d2.Z);
        }
示例#22
0
        public bool IsPositionBlocked(Position position)
        {
            var positionHasBot = Bots.Any(b => b.Position.Equals(position));
            var positionHasBlockingGameObject =
                this.GameObjects.Any(gi => gi.IsBlocking && gi.Position.Equals(position));

            return(positionHasBot ||
                   positionHasBlockingGameObject);
        }
示例#23
0
        public void CmdFission(int bid, Coordinate c, int m)
        {
            if (!Bots.TryGetValue(bid, out var bot))
            {
                throw new CommandException("fission", "bot does not exist");
            }

            throw new NotImplementedException();
        }
示例#24
0
 public void Reset()
 {
     Bots.Clear();
     Bombs.Clear();
     Missiles.Clear();
     Explosions.Clear();
     Board = new BoardTile[Board.GetLength(0), Board.GetLength(1)];
     OnArenaChanged();
 }
示例#25
0
        public bool IsFull()
        {
            var size = Width * Height;
            var bots = Bots.Count();

            // Consider >10% of the board to be full
            // E.g. 10x10 with 10 bots is considered full
            return(bots > (int)(size * 0.1));
        }
示例#26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Resources"/> class.
        /// </summary>
        internal static void Initialize()
        {
            if (!Resources.Started)
            {
                Resources.Bots = new Bots();
            }

            Resources.Started = true;
        }
 public IActionResult Put([FromBody] Bots bot)
 {
     if (ModelState.IsValid)
     {
         _dataAccessProvider.UpdateBot(bot);
         return(Ok());
     }
     return(BadRequest());
 }
		public void GetDefault_None_ParametersToString()
		{
			var pars = EvaluatorParameters.GetDefault();
			var act = BotData.ParametersToString(pars);
			Console.Write(act);

			var bots = new Bots();
			bots.Add(pars);
			bots.Save(new FileInfo("default.xml"));
		}
示例#29
0
        /// <summary>
        /// Executes the tick in all Bot instances.
        /// </summary>
        public static void Tick()
        {
            if (SynchronizationContext.Current == null)
            {
                SynchronizationContext.SetSynchronizationContext(SyncContext);
            }

            ReCheck();
            Bots.ForEach(bot => bot.Tick(SyncContext));
        }
示例#30
0
        public bool CanSpawnMoreBots(MyPlayer.PlayerId pid)
        {
            if (!Sync.IsServer)
            {
                Debug.Assert(false, "Server only");
                return(false);
            }

            if (MyFakes.ENABLE_BRAIN_SIMULATOR)
            {
                return(true);
            }

            if (MyFakes.DEVELOPMENT_PRESET)
            {
                return(true);
            }

            if (MySteam.UserId == pid.SteamId)
            {
                AgentSpawnData spawnData = default(AgentSpawnData);
                if (m_agentsToSpawn.TryGetValue(pid.SerialId, out spawnData))
                {
                    if (spawnData.CreatedByPlayer)
                    {
                        return(Bots.GetCreatedBotCount() < BotFactory.MaximumBotPerPlayer);
                    }
                    else
                    {
                        return(Bots.GetGeneratedBotCount() < BotFactory.MaximumUncontrolledBotCount);
                    }
                }
                else
                {
                    Debug.Assert(false, "Bot doesn't exist");
                    return(false);
                }
            }
            else
            {
                int botCount     = 0;
                var lookedPlayer = pid.SteamId;
                var players      = Sync.Players.GetOnlinePlayers();

                foreach (var player in players)
                {
                    if (player.Id.SteamId == lookedPlayer && player.Id.SerialId != 0)
                    {
                        botCount++;
                    }
                }

                return(botCount < BotFactory.MaximumBotPerPlayer);
            }
        }
示例#31
0
 private void ResetState()
 {
     LiveAccounts.Clear();
     DemoAccounts.Clear();
     Accounts.Clear();
     accountsByName.Clear();
     Bots.Clear();
     //Alerts.Clear();
     Sessions.Clear();
     State = ExecutionStateEx.Uninitialized;
 }
示例#32
0
		public void GetRandom_NoActive_IsNull()
		{
			var bots = new Bots();
            bots.Add(new Bot() { Info = new BotInfo("Engine1", 0, true) });

			var rnd = new Random(17);

			var act = bots.GetRandom(rnd);

			Assert.IsNull(act);
		}
		public BattleSimulator(MT19937Generator rnd)
		{
			File = new FileInfo("parameters.xml");
			SearchDepth = AppConfig.Data.SearchDepth;

			Rnd = rnd;
			Randomizer = new ParameterRandomizer(rnd);

			Bots = new Bots();
			Results = new ConcurrentQueue<BattlePairing>();
		}
示例#34
0
		public void GetOrCreate_Existing_AreEqual()
		{
			var info = new BotInfo("Engine1", 0);

			var bots = new Bots();
            bots.Add(new Bot() { Info = new BotInfo("Engine1", 0, true) });

			var act = bots.GetOrCreate(info);

			Assert.AreEqual(1, bots.Count, "bots.Count");
			Assert.AreEqual("Engine1", act.Info.Name, "Name");
			Assert.AreEqual(false, act.Info.Inactive, "Inactive");
		}
示例#35
0
		public void GetRandom_Seed17_AreEqual()
		{
            var exp = new Bot() { Info = new BotInfo("Engine4") };

			var bots = new Bots();
            bots.Add(new Bot() { Info = new BotInfo("Engine1", 0, true) });
            bots.Add(new Bot() { Info = new BotInfo("Engine2", 0, true) });
            bots.Add(new Bot() { Info = new BotInfo("Engine3", 0, true) });
			bots.Add(exp);

			var rnd = new Random(17);

			var act = bots.GetRandom(rnd);

			Assert.AreEqual(exp, act);
		}